Webhook

借助 Webhook,Gemini API 可以在异步操作或长时间运行的操作 (LRO) 完成时,向您的服务器推送实时通知。这样一来,就不再需要轮询 API 以获取状态更新,从而缩短延迟时间并减少开销。

Webhook 可用于批量作业、互动视频生成等操作。

运作方式

您可以配置 Gemini API Webhook,以便在事件触发时立即向监听器网址发送 HTTP POST 请求,而无需反复轮询 GET /operations 来检查作业是否已完成。

Gemini API 支持两种配置网络钩子的方式:

  • 静态 Webhook:使用 Gemini WebhookService API 配置的项目级端点。适用于全局集成(例如,通知 Slack、同步数据库等)。
  • 动态网络钩子:请求级替换,在特定作业调用的配置载荷中传递网络钩子网址。非常适合将特定作业路由到专用端点。

静态 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 的详细信息。

Python

from google import genai

client