Dependencies FastStream uses the secondary library FastDepends for dependency management. This dependency system is literally borrowed from FastAPI , so if you know how to work with that framework, you'll be comfortable with dependencies in FastStream .
You can visit the FastDepends documentation for more details, but the key points and additions are covered here.
Type Casting The key function in the dependency management and type conversion system in FastStream is the decorator @apply_types (also known as @inject in FastDepends ).
By default, it applies to all event handlers, unless you disable this option when creating the broker.
Warning
Setting the apply_types=False flag not only disables type casting but also Depends and Context. If you want to disable only type casting, use serializer=None instead.
This flag can be useful if you are using FastStream within another framework and you need to use its native dependency system.
Using Annotated Dependencies can also be used with Annotated.
Dependency Injection To implement dependencies in FastStream , a special class called Depends is used.
AIOKafka Confluent RabbitMQ NATS Redis MQTT
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.kafka import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.confluent import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.rabbit import RabbitBroker
broker = RabbitBroker ( "amqp://guest:guest@localhost:5672/" )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.nats import NatsBroker
broker = NatsBroker ( "nats://localhost:4222" )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.redis import RedisBroker
broker = RedisBroker ( "redis://localhost:6379" )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
1
2
3
4
5
6
7
8
9
10
11
12 from faststream import FastStream , Depends
from faststream.mqtt import MQTTBroker
broker = MQTTBroker ( "localhost" , port = 1883 )
app = FastStream ( broker )
def simple_dependency () -> int :
return 1
@broker . subscriber ( "test" )
async def handler ( body : dict , d : int = Depends ( simple_dependency )):
assert d == 1
The first step : You need to declare a dependency, which can be any Callable object.
Callable A "Callable" is an object that can be "called". It can be a function, a class, or a class method.
In other words, if you can write code like my_object() - my_object is Callable
Second step : Declare which dependencies you need using Depends
The last step : Use the result of executing your dependency!
Top-level Dependencies If you don't need a dependency result, you can use the following code:
@broker . subscriber ( "test" )
def method ( _ = Depends ( ... )): ...
But, using a special subscriber parameter is much more suitable:
@broker . subscriber ( "test" , dependencies = [ Depends ( ... )])
def method (): ...
You can also declare broker-level dependencies, which will be applied to all of the broker's handlers:
broker = RabbitBroker ( dependencies = [ Depends ( ... )])
Nested Dependencies Dependencies can also contain other dependencies. This works in a very predictable way: just declare Depends in the dependent function.
AIOKafka Confluent RabbitMQ NATS Redis MQTT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.kafka import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.confluent import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.rabbit import RabbitBroker
broker = RabbitBroker ( "amqp://guest:guest@localhost:5672/" )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.nats import NatsBroker
broker = NatsBroker ( "nats://localhost:4222" )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.redis import RedisBroker
broker = RedisBroker ( "redis://localhost:6379" )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from faststream import FastStream , Depends
from faststream.mqtt import MQTTBroker
broker = MQTTBroker ( "localhost" , port = 1883 )
app = FastStream ( broker )
def another_dependency () -> int :
return 1
def simple_dependency ( b : int = Depends ( another_dependency )) -> int : # (1)
return b * 2
@broker . subscriber ( "test" )
async def handler (
body : dict ,
a : int = Depends ( another_dependency ),
b : int = Depends ( simple_dependency ),
):
assert a + b == 3
A nested dependency is called here Auto @apply_types
In the code above, we didn't use this decorator on our simple_dependency. However, it still automatically applies to all functions used as dependencies.
Caching
In the example above, the another_dependency function will be called only ONCE ! FastDepends caches all dependency execution results within ONE @apply_types call stack. This means that all nested dependencies will receive the cached result of dependency execution. But, between different calls of the main function, these results will be different.
To prevent this behavior, just use Depends ( ... , use_cache = False ) . In this case, the dependency will be used for each function in the call stack where it is used.
Dependencies with yield A dependency can be a generator. The code before yield runs before the handler, the yielded value is injected into it, and the code after yield runs when the handler has finished, before its result is published. This is the way to open a resource for a message and release it afterwards, like a database session.
AIOKafka Confluent RabbitMQ NATS Redis MQTT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.kafka import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.confluent import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.rabbit import RabbitBroker
broker = RabbitBroker ( "amqp://guest:guest@localhost:5672/" )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.nats import NatsBroker
broker = NatsBroker ( "nats://localhost:4222" )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.redis import RedisBroker
broker = RedisBroker ( "redis://localhost:6379" )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 from faststream import FastStream , Depends
from faststream.mqtt import MQTTBroker
broker = MQTTBroker ( "localhost" , port = 1883 )
app = FastStream ( broker )
class Session :
closed = False
def close ( self ) -> None :
self . closed = True
async def get_session ():
session = Session ()
try :
yield session
finally :
session . close ()
@broker . subscriber ( "test" )
async def handler ( body : dict , session : Session = Depends ( get_session )):
assert not session . closed
Note
If the handler raises, the exception is raised inside the dependency at yield, so put the cleanup in finally to run it anyway. If the dependency catches the exception, it must re-raise it: suppressing the handler's exception is not supported.
Note
Both generators and async generators work. For a real-world example, see the In-Progress sender for NATS.
Use with Regular Functions You can use the decorator @apply_types not only with @broker . subscriber ( ... ) , but also with regular functions, both synchronous and asynchronous.
Sync Async
from faststream import Depends , apply_types
def simple_dependency ( a : int , b : int = 3 ) -> int :
return a + b
@apply_types
def method ( a : int , d : int = Depends ( simple_dependency )) -> int :
return a + d
def test_sync_dependency () -> None :
assert method ( 1 ) == 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import asyncio
import pytest
from faststream import Depends , apply_types
async def simple_dependency ( a : int , b : int = 3 ) -> int :
return a + b
def another_dependency ( a : int ) -> int :
return a
@apply_types
async def method (
a : int ,
b : int = Depends ( simple_dependency ),
c : int = Depends ( another_dependency ),
):
return a + b + c
@pytest . mark . asyncio
async def test_async_dependency () -> None :
assert 6 == await method ( 1 )
Be careful
In asynchronous code, you can use both synchronous and asynchronous dependencies. But in synchronous code, only synchronous dependencies are available to you.
Casting Dependency Types FastDepends , used by FastStream , also casts the return type. This means that the value returned by the dependency will be cast to the type twice: as return for dependencies and as the input argument of the main function. This does not incur additional costs if these types have the same annotation. Just keep it in mind. Or not... Anyway, I've warned you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 from faststream import Depends , apply_types
def simple_dependency ( a : int , b : int = 3 ) -> str :
# NOTE: This will make type-checkers unhappy,
# it is better to avoid this pattern in production code!
return a + b # 'return' is cast to `str` for the first time
@apply_types
def method ( a : int , d : int = Depends ( simple_dependency )):
# 'd' is cast to `int` for the second time
return a + d
# NOTE: This will make type-checkers unhappy,
# it is better to avoid this pattern in production code!
assert method ( "1" ) == 5
Also, the result of executing the dependency is cached. If you use this dependency in N functions, this cached result will be converted to type N times (at the input to the function being used).
To avoid problems with this, use mypy or just be careful with the annotation of types in your project.
Dependency overrides To override your dependencies, you need to use a Provider from FastDepends
You can override them either at the application level by passing a Provider to FastStream
class Service ( ABC ):
@abstractmethod
def action ( self ) -> None :
raise NotImplementedError
class ServiceImpl ( Service ):
@override
def action ( self ) -> None :
pass
provider = Provider ()
provider . override ( Service , ServiceImpl )
app = FastStream ( provider = provider )
Or specifically for a particular broker
Overriding Dependencies in Tests The main use case for overrides is tests: replace a database client or an external service while the handler runs under the test broker. broker . provider . scope ( original , override ) overrides a dependency inside the with block and removes the override on exit.
AIOKafka Confluent RabbitMQ NATS Redis MQTT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.kafka import KafkaBroker , TestKafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestKafkaBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.confluent import KafkaBroker , TestKafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestKafkaBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.rabbit import RabbitBroker , TestRabbitBroker
broker = RabbitBroker ( "amqp://guest:guest@localhost:5672/" )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestRabbitBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.nats import NatsBroker , TestNatsBroker
broker = NatsBroker ( "nats://localhost:4222" )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestNatsBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.redis import RedisBroker , TestRedisBroker
broker = RedisBroker ( "redis://localhost:6379" )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestRedisBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import pytest
from faststream import FastStream , Depends
from faststream.mqtt import MQTTBroker , TestMQTTBroker
broker = MQTTBroker ( "localhost" , port = 1883 )
app = FastStream ( broker )
def get_client () -> str :
return "real client"
@broker . subscriber ( "test" )
async def handler ( body : dict , client : str = Depends ( get_client )) -> str :
return client
def get_fake_client () -> str :
return "fake client"
@pytest . mark . asyncio
async def test_handler () -> None :
with broker . provider . scope ( get_client , get_fake_client ):
async with TestMQTTBroker ( broker ) as br :
response = await br . request ({}, "test" )
assert await response . decode () == "fake client"
An override on a broker also applies to the handlers of the routers included in it.
Warning
A broker created without provider uses the global provider of FastDepends , which is shared by every such broker. An override made through one of them applies to all of them, and clear() removes overrides made through any of them. Pass a separate Provider () to the broker to keep its overrides to itself.
Handlers of the FastAPI integration resolve dependencies with FastAPI itself, so override them with its dependency_overrides .