Google CloudEvents Python Library

0.14.0 · active · verified Wed Apr 15

The `google-events` library provides strongly-typed data payload schemas (using `proto-plus`) for various Google Cloud services that emit CloudEvents. It helps developers safely deserialize and interact with event data, ensuring type correctness and reducing runtime errors. The library is actively maintained by Google and sees frequent updates, primarily adding new event types and fields as Google Cloud services evolve.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to deserialize a raw JSON event data payload (e.g., from a Cloud Storage object finalization event) into a `StorageObjectData` object and access its strongly-typed properties.

import json
from google.events.cloud.storage.v1 import StorageObjectData

# Simulate a raw CloudEvent 'data' payload for a GCS object finalization
# This would typically come from an HTTP request body or Pub/Sub message.
raw_event_data = {
    "bucket": "my-test-bucket",
    "name": "my-folder/new-file.txt",
    "contentType": "text/plain",
    "size": "12345",
    "storageClass": "STANDARD",
    "timeCreated": "2023-10-27T10:00:00.000Z",
    "updated": "2023-10-27T10:00:00.000Z"
}

# Deserialize the raw JSON data into a strongly-typed StorageObjectData object
storage_object_data = StorageObjectData.from_json(json.dumps(raw_event_data))

# Access properties with type safety
print(f"Bucket: {storage_object_data.bucket}")
print(f"Object Name: {storage_object_data.name}")
print(f"Content Type: {storage_object_data.content_type}")
print(f"Size: {storage_object_data.size}")

# Example of a field that might not always be present (e.g., etag)
if storage_object_data.etag: # proto-plus fields return None or default for missing/empty
    print(f"ETag: {storage_object_data.etag}")
else:
    print("ETag not present in event data.")

view raw JSON →