Skip to content

Emulator and credentials#

The emulator#

The broker connects to the Pub/Sub emulator, with no credentials, when the PUBSUB_EMULATOR_HOST variable is set or emulator_host is passed.

service.py
from faststream import FastStream

from faststream_gcp_pubsub import PubSubBroker

# also read from PUBSUB_EMULATOR_HOST when the argument is omitted
broker = PubSubBroker(project_id="faststream-test", emulator_host="localhost:8085")
app = FastStream(broker)


@broker.subscriber("orders-billing", topic="orders")
async def bill(order: dict[str, int]) -> None: ...

emulator_host=None connects to Google Cloud even when the variable is set. The getting started page shows how to start the emulator with the repository's docker-compose.yaml.

Project#

project_id names the project short topic and subscription names belong to. When it is omitted, the broker reads GOOGLE_CLOUD_PROJECT.

Credentials#

Without a security object the broker uses Application Default Credentials: the GOOGLE_APPLICATION_CREDENTIALS key file, the gcloud login, or the metadata server of Google Cloud. GCPSecurity passes other credentials.

service.py
from google.oauth2 import service_account

from faststream_gcp_pubsub import GCPSecurity, PubSubBroker


def from_key_file() -> PubSubBroker:
    return PubSubBroker(
        project_id="my-project",
        security=GCPSecurity.from_service_account_file("key.json"),
    )


def from_credentials() -> PubSubBroker:
    credentials = service_account.Credentials.from_service_account_file("key.json")
    return PubSubBroker(project_id="my-project", security=GCPSecurity(credentials))

GCPSecurity also has from_service_account_info, which takes the parsed JSON key. Any google.auth credentials object works with GCPSecurity(credentials).

Endpoints and client options#

api_endpoint selects a regional or private endpoint. client_options passes other google.api_core.client_options to both clients.

service.py
from faststream_gcp_pubsub import PubSubBroker

broker = PubSubBroker(
    project_id="my-project",
    api_endpoint="europe-west1-pubsub.googleapis.com:443",
    client_options={"quota_project_id": "billing-project"},
)