Skip to content

Getting started#

A service is a broker, a FastStream app and handlers.

service.py
import logging

from faststream import FastStream
from pydantic import BaseModel

from faststream_sqs_sns import CapoSqsBroker, SqsQueue


class Order(BaseModel):
    id: int
    amount: float


broker = CapoSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)


@broker.subscriber(SqsQueue("orders", declare=True))
async def bill(order: Order) -> None:
    logger.info("billing order %s", order.id)


@app.after_startup
async def place_order() -> None:
    await broker.publish(Order(id=1, amount=9.5), "orders")

The handler reads the queue orders. declare=True creates the queue at startup when it does not exist. The broker is built without any network call; it connects when the app starts.

Run the service#

Install the capo and cli extras, then start the app with the faststream command:

pip install "faststream-sqs-sns[capo,cli]"
faststream run service:app

The broker finds credentials and the region the way the AWS tools do: environment variables, the shared config, or the role of the host. LocalStack and credentials shows how to run against LocalStack and how to pass keys. To run it against AWS, give the service permission to call sqs:CreateQueue, sqs:GetQueueUrl, sqs:GetQueueAttributes, sqs:ReceiveMessage, sqs:DeleteMessage, sqs:ChangeMessageVisibility and sqs:SendMessage.

Pick the other backend#

AiobotocoreSqsBroker takes the same arguments and runs the same handlers:

service.py
import logging

from faststream import FastStream

from faststream_sqs_sns import AiobotocoreSqsBroker, SqsQueue

# the same handlers run on either backend: only the class of the broker changes
broker = AiobotocoreSqsBroker(region="eu-central-1")
app = FastStream(broker)
logger = logging.getLogger(__name__)


@broker.subscriber(SqsQueue("orders", declare=True))
async def bill(order: dict[str, int]) -> None:
    logger.info("billing order %s", order["id"])

Install faststream-sqs-sns[aiobotocore] for it. Choosing a backend lists what differs.

Test the service#

TestSqsBroker runs the handlers in process:

test_service.py
    async with TestSqsBroker(broker) as br:
        await br.publish(Order(id=1, amount=9.5), "orders")

        bill.mock.assert_called_once_with({"id": 1, "amount": 9.5})

Read Testing for the routing and validation rules of the in-process broker.