Webhook

當非同步或長時間執行的作業 (LRO) 完成時,Webhook 可讓 Gemini API 將即時通知推送至伺服器。這項功能可取代輪詢 API 狀態更新的需求,減少延遲和額外負荷。

Webhook 適用於批次作業、互動影片生成等作業。

運作方式

您不必重複輪詢 GET /operations 來檢查工作是否完成,可以設定 Gemini API Webhook,在事件觸發時立即向接聽程式網址傳送 HTTP POST 要求。

Gemini API 支援兩種設定 Webhook 的方式:

  • 靜態 Webhook:使用 Gemini WebhookService API 設定的專案層級端點。適合用於全域整合 (例如通知 Slack、同步處理資料庫等)。
  • 動態 Webhook:要求層級的覆寫,在特定工作呼叫的設定酬載中傳遞 Webhook 網址。適合將特定工作路由至專屬端點。

靜態 Webhook

系統會為整個專案註冊靜態 Webhook,並針對任何相符的事件觸發。

建立 Webhook

您可以使用 SDK 或 REST API 建立端點。

重要事項:建立 Webhook 時,API 只會傳回一次 簽署密鑰。您必須安全地儲存這項資訊 (例如儲存在環境變數中),以便稍後驗證簽章。如果遺失簽署密鑰,就必須輪換密鑰。

Python

from google import genai

client = genai.Client()

webhook = client.webhooks.create(
    name="MyBatchWebhook",
    subscribed_events=["batch.succeeded", "batch.failed"],
    uri="https://my-api.com/gemini-callback",
)

# Store webhook.new_signing_secret securely
webhook_secret = webhook.new_signing_secret
print(f"Created webhook: {webhook.name}, {webhook.id}")

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI();

async function createWebhook() {
  const webhook = await client.webhooks.create({
    name: "MyBatchWebhook",
    subscribed_events: ["batch.succeeded", "batch.failed"],
    uri: "https://my-api.com/gemini-callback",
  });

  // Store webhook.signingSecret securely
  const webhookSecret = webhook.new_signing_secret;
  console.log(`Created webhook: ${webhook.name}, ${webhook.id}`);
}

createWebhook();

REST

curl -X POST \
  "https://generativelanguage.googleapis.com/v1/webhooks" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
    "name": "MyBatchWebhook",
    "uri": "https://my-api.com/gemini-callback",
    "subscribed_events": ["batch.succeeded", "batch.failed"]
  }'

如要瞭解如何設定伺服器來接收資料,請參閱「處理 Webhook 要求」一節。

取得 Webhook

依資源名稱擷取特定 Webhook 的詳細資料。

Python

from google import genai

client = genai.Client()

webhook = client.webhooks.get(id="<your_webhook_id>")

print(f"Webhook: {webhook.name}")
print(