Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

FastStream

Effortless event stream integration for your services


Test PassingCoverageDownloadsPackage versionSupported Python versions
CodeQLDependency ReviewLicenseCode of ConductDiscord


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, NATS, Redis 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

  • Extensible: Use extensions for lifespans, custom serialization and middleware

  • 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.


Documentation: https://faststream.airt.ai/latest/


History

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 a 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.


Install

FastStream works on Linux, macOS, Windows and most Unix-style operating systems. You can install it with pip as usual:

pip install faststream[kafka]
# or
pip install faststream[rabbit]
# or
pip install faststream[nats]
# or
pip install faststream[redis]

By default FastStream uses PydanticV2 written in Rust, but you can downgrade it manually, if your platform has no Rust support - FastStream will work correctly with PydanticV1 as well.


Writing app code

FastStream brokers provide convenient function decorators @broker.subscriber and @broker.publisher to allow you to delegate the actual process of:

  • consuming and producing data to Event queues, and

  • decoding and encoding JSON-encoded messages

These decorators make it easy to specify the processing logic for your consumers and producers, allowing you to focus on the core business logic of your application without worrying about the underlying integration.

Also, FastStream uses Pydantic to parse input JSON-encoded data into Python objects, making it easy to work with structured data in your applications, so you can serialize your input messages just using type annotations.

Here is an example Python app using FastStream that consumes data from an incoming data stream and outputs the data to another one:

fromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBroker# from faststream.rabbit import RabbitBroker# from faststream.nats import NatsBroker# from faststream.redis import RedisBrokerbroker=KafkaBroker("localhost:9092")
# broker = RabbitBroker("amqp://guest:guest@localhost:5672/")# broker = NatsBroker("nats://localhost:4222/")# broker = RedisBroker("redis://localhost:6379/")app=FastStream(broker)
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(user: str, user_id: int) ->str:
returnf"User: {user_id} - {user} registered"

Also, Pydantic’s BaseModel class allows you to define messages using a declarative syntax, making it easy to specify the fields and types of your messages.

frompydanticimportBaseModel, Field, PositiveIntfromfaststreamimportFastStreamfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
app=FastStream(broker)
classUser(BaseModel):
user: str=Field(..., examples=["John"])
user_id: PositiveInt=Field(..., examples=["1"])
@broker.subscriber("in")@broker.publisher("out")asyncdefhandle_msg(data: User) ->str:
returnf"User: {data.user} - {data.user_id} registered"

Testing the service

The service can be tested using the TestBroker context managers, which, by default, puts the Broker into "testing mode".

The Tester will redirect your subscriber and publisher decorated functions to the InMemory brokers, allowing you to quickly test your app without the need for a running broker and all its dependencies.

Using pytest, the test for our service would look like this:

# Code above omitted 👆importpytestimportpydanticfromfaststream.kafkaimportTestKafkaBroker@pytest.mark.asyncioasyncdeftest_correct():
asyncwithTestKafkaBroker(broker) asbr:
awaitbr.publish({
"user": "John",
"user_id": 1,
}, "in")
@pytest.mark.asyncioasyncdeftest_invalid():
asyncwithTestKafkaBroker(broker) asbr:
withpytest.raises(pydantic.ValidationError):
awaitbr.publish("wrong message", "in")

Running the application

The application can be started using built-in FastStream CLI command.

To run the service, use the FastStream CLI command and pass the module (in this case, the file where the app implementation is located) and the app symbol to the command.

faststream run basic:app

After running the command, you should see the following output:

INFO - FastStream app starting...
INFO - input_data | - `HandleMsg` waiting for messages
INFO - FastStream app started successfully! To exit press CTRL+C

Also, FastStream provides you with a great hot reload feature to improve your Development Experience

faststream run basic:app --reload

And multiprocessing horizontal scaling feature as well:

faststream run basic:app --workers 3

You can learn more about CLI features here


Project Documentation

FastStream automatically generates documentation for your project according to the AsyncAPI specification. You can work with both generated artifacts and place a web view of your documentation on resources available to related teams.

The availability of such documentation significantly simplifies the integration of services: you can immediately see what channels and message formats the application works with. And most importantly, it won't cost anything - FastStream has already created the docs for you!

HTML-page


Dependencies

FastStream (thanks to FastDepends) has a dependency management system similar to pytest fixtures and FastAPI Depends at the same time. Function arguments declare which dependencies you want are needed, and a special decorator delivers them from the global Context object.

fromfaststreamimportDepends, Loggerasyncdefbase_dep(user_id: int) ->bool:
returnTrue@broker.subscriber("in-test")asyncdefbase_handler(user: str,
logger: Logger,
dep: bool=Depends(base_dep)):
assertdepisTruelogger.info(user)

HTTP Frameworks integrations

Any Framework

You can use FastStreamMQBrokers without a FastStream application. Just start and stop them according to your application's lifespan.

fromaiohttpimportwebfromfaststream.kafkaimportKafkaBrokerbroker=KafkaBroker("localhost:9092")
@broker.subscriber("test")asyncdefbase_handler(body):
print(body)
asyncdefstart_broker(app):
awaitbroker.start()
asyncdefstop_broker(app):
awaitbroker.close()
asyncdefhello(request):
returnweb.Response(text="Hello, world")
app=web.Application()
app.add_routes([web.get("/", hello)])
app.on_startup.append(start_broker)
app.on_cleanup.append(stop_broker)
if__name__=="__main__":
web.run_app(app)

FastAPI Plugin

Also, FastStream can be used as part of FastAPI.

Just import a StreamRouter you need and declare the message handler with the same @router.subscriber(...) and @router.publisher(...) decorators.

fromfastapiimportFastAPIfrompydanticimportBaseModelfromfaststream.kafka.fastapiimportKafkaRouterrouter=KafkaRouter("localhost:9092")
classIncoming(BaseModel):
m: dict@router.subscriber("test")@router.publisher("response")asyncdefhello(m: Incoming):
return {"response": "Hello, world!"}
app=FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

More integration features can be found here


Code generator

As evident, FastStream is an incredibly user-friendly framework. However, we've taken it a step further and made it even more user-friendly! Introducing faststream-gen, a Python library that harnesses the power of generative AI to effortlessly generate FastStream applications. Simply describe your application requirements, and faststream-gen will generate a production-grade FastStream project that is ready to deploy in no time.

Save application description inside description.txt:

Create a FastStream application using localhost broker for testing and use the
default port number.
It should consume messages from the 'input_data' topic, where each message is a
JSON encoded object containing a single attribute: 'data'.
While consuming from the topic, increment the value of the data attribute by 1.
Finally, send message to the 'output_data' topic.

and run the following command to create a new FastStream project:

faststream_gen -i description.txt
✨ Generating a new FastStream application!
✔ Application description validated.
✔ FastStream app skeleton code generated. akes around 15 to 45 seconds)...
✔ The app and the tests are generated. around 30 to 90 seconds)...
✔ New FastStream project created.
✔ Integration tests were successfully completed.
Tokens used: 10768
Total Cost (USD): $0.03284
✨ All files were successfully generated!

Tutorial

We also invite you to explore our tutorial, where we will guide you through the process of utilizing the faststream-gen Python library to effortlessly create FastStream applications:


Stay in touch

Please show your support and stay in touch by:

Your support helps us to stay in touch with you and encourages us to continue developing and improving the framework. Thank you for your support!


Contributors

Thanks to all of these amazing people who made the project better!

About

FastStream is a powerful and easy-to-use Python framework for building asynchronous services that interact with event streams such as Apache Kafka and RabbitMQ.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages