Webhook
Webhook 允许 Gemini API 在异步或长时间运行操作 (LRO) 完成时将实时通知推送到您的服务器。这取代了轮询 API 状态更新的需要,从而减少了延迟和开销。
Webhooks 可用于以下操作 批次 工作岗位, 互动 和 视频生成.
它是如何运作的 #
而不是轮询 GET /operations 重复检查作业是否完成,您可以配置 Gemini API Webhooks 在事件触发时立即向侦听器 URL 发送 HTTP POST 请求。
Gemini API 支持两种配置 Webhook 的方式:
- 静态网络钩子:使用 Gemini 配置的项目级端点 Webhook服务 API。适合全球集成(例如,通知 Slack、同步数据库等)。
- 动态网络钩子:请求级别覆盖在特定作业调用的配置负载中传递 Webhook URL。非常适合将特定作业路由到专用端点。
静态网络钩子 #
静态 webhook 是整体注册的 项目 并触发任何匹配的事件。
创建网络钩子 #
您可以使用 SDK 或 REST API 创建端点。
IMPORTANT:创建 webhook 时,API 返回一个 签名秘密 只有一次。您必须安全地存储它(例如在环境变量中)以便稍后验证签名。如果您丢失了签名密钥,则必须 旋转 它。
from google import genai
client = genai.Client(http_options={"api_version": "v1beta"})
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}")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
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}`);
}
await createWebhook();
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/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 的详细信息。
from google import genai
client = genai.Client(http_options={"api_version": "v1beta"})
webhook = client.webhooks.get(id="<your_webhook_id>")
print(f"Webhook: {webhook.name}")
print(f"URI: {webhook.uri}")
print(f"Events: {webhook.subscribed_events}")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } }); // Assumes process.env.GEMINI_API_KEY is set
async function getWebhook() {
const webhook = await client.webhooks.get("<your_webhook_id>");
console.log(`Webhook: ${webhook.name}`);
console.log(`URI: ${webhook.uri}`);
console.log(`Events: ${webhook.subscribed_events}`);
}
await getWebhook();
curl -X GET \
"https://generativelanguage.googleapis.com/v1beta/webhooks/<your_webhook_id>" \
-H "x-goog-api-key: $GEMINI_API_KEY"
列出网络钩子 #
列出当前项目的所有配置的 webhook,并带有可选的分页。
from google import genai
client = genai.Client(http_options={"api_version": "v1beta"})
webhooks = client.webhooks.list()
for wh in webhooks:
print(f"{wh.id}: {wh.name} -> {wh.uri}")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
async function listWebhooks() {
const webhooks = await client.webhooks.list();
for (const wh of webhooks) {
console.log(`${wh.id}: ${wh.name} -> ${wh.uri}`);
}
}
await listWebhooks();
curl -X GET \
"https://generativelanguage.googleapis.com/v1beta/webhooks" \
-H "x-goog-api-key: $GEMINI_API_KEY"
更新网络钩子 #
更新现有 Webhook 的属性,例如显示名称、目标 URI 或订阅的事件。
from google import genai
client = genai.Client(http_options={"api_version": "v1beta"})
updated_webhook = client.webhooks.update(
id="<your_webhook_id>",
subscribed_events=["batch.succeeded", "batch.failed", "batch.cancelled"],
)
print(f"Updated webhook: {updated_webhook.name}")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
async function updateWebhook() {
const updatedWebhook = await client.webhooks.update(
"<your_webhook_id>",
{
subscribed_events: ["batch.succeeded", "batch.failed", "batch.cancelled"],
}
);
console.log(`Updated webhook: ${updatedWebhook.name}`);
}
await updateWebhook();
curl -X PATCH \
"https://generativelanguage.googleapis.com/v1beta/webhooks/<your_webhook_id>" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"subscribed_events": ["batch.succeeded", "batch.failed", "batch.cancelled"]
}'
删除网络钩子 #
从项目中删除 webhook 端点。这会阻止将来的事件传递到该端点。
from google import genai
client = genai.Client(http_options={"api_version": "v1beta"})
client.webhooks.delete(id="<your_webhook_id>")
print("Webhook deleted.")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
async function deleteWebhook() {
await client.webhooks.delete("<your_webhook_id>");
console.log("Webhook deleted.");
}
await deleteWebhook();
curl -X DELETE \
"https://generativelanguage.googleapis.com/v1beta/webhooks/<your_webhook_id>" \
-H "x-goog-api-key: $GEMINI_API_KEY"
轮换签名秘密 #
轮换 Webhook 的签名密钥。您可以配置是立即撤销之前有效的密钥,还是在 24 小时的宽限期后撤销。
IMPORTANT:返回新的签名密钥 只有一次 在旋转时间。在更新验证逻辑之前安全地存储它。
from google import genai
from google.genai import types
client = genai.Client(http_options={"api_version": "v1beta"})
response = client.webhooks.rotate_signing_secret(
id="<your_webhook_id>",
revocation_behavior="REVOKE_PREVIOUS_SECRETS_AFTER_H24",
)
# Store response.secret securely, then update your server's verification config
print("New signing secret generated. Update your server configuration.")
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
async function rotateSigningSecret() {
const response = await client.webhooks.rotateSigningSecret(
"<your_webhook_id>",
{
revocation_behavior: "REVOKE_PREVIOUS_SECRETS_AFTER_H24",
}
);
// Store response.secret securely, then update your server's verification config
console.log("New signing secret generated. Update your server configuration.");
}
await rotateSigningSecret();
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/webhooks/<your_webhook_id>/rotate_secret" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"revocation_behavior": "REVOKE_PREVIOUS_SECRETS_AFTER_H24"
}'
处理服务器上的 Webhook 请求 #
当您订阅的事件发生时,您的 Webhook URL 将收到 HTTP POST 请求。您的端点必须在几秒钟内响应 2xx 状态代码以避免重试。为了确保交付,Gemini API 使用指数退避在 24 小时内自动重试失败的请求。
Gemini严格遵循 标准 Webhooks 安全标头规范。使用签名的标头签名和存储的静态签名密钥验证服务器上的有效负载。请参阅 Webhook 信封 有效负载信息部分。
以下是使用 Flask 作为 HTTP 侦听器的示例:
# pip install flask standardwebhooks
import os
from flask import Flask, request, jsonify
# Standard verification wrapper for Standard Webhook Headers
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
app = Flask(__name__)
SIGNING_SECRET = os.environ.get('WEBHOOK_SIGNING_SECRET')
@app.route('/gemini-callback', methods=['POST'])
def gemini_callback():
payload = request.get_data(as_text=True)
headers = request.headers
try:
wh = Webhook(SIGNING_SECRET)
event = wh.verify(payload, headers)
except WebhookVerificationError as e:
return jsonify({"error": "Signature invalid"}), 400
# Process thin payload contents
if event.get("type") == "batch.succeeded":
print(f"Batch completed! ID: {event["data"]["id"]}")
if event["data"].get("output_file_uri"):
# For batch jobs with input file
print(f"Batch file: {event["data"]["output_file_uri"]}")
elif (event.type == "video.generated"):
print(f"Video generated! URI: {event["data"]["output_file_uri"]}")
return jsonify({"status": "received"}), 200
if __name__ == "__main__":
app.run(port=8000)
// npm install standardwebhooks
import { Webhook } from "standardwebhooks";
import express from "express";
const app = express();
const client = new GoogleGenAI({ webhookSecret: process.env.WEBHOOK_SIGNING_SECRET });
// Don't use express.json() because signature verification needs the raw text body
app.use(express.text({ type: "application/json" }));
app.post("/gemini-callback", async (req, res) => {
const payload = await req.text();
const headers: Record<string, string> = {};
req.headers.forEach((value, key) => {
headers[key] = value;
});
try {
const wh = new Webhook(process.env.WEBHOOK_SIGNING_SECRET);
const event = wh.verify(payload, headers) as Record<string, any>;
console.log(`Event type: ${event.type}, data: ${JSON.stringify(event.data)}`);
// Process thin payload contents
if (event.type === "batch.succeeded") {
console.log(`Batch completed! ID: ${event.data.id}`);
if (event.data.output_file_uri) {
// For batch jobs with input file
console.log(`Batch file: ${event.data.output_file_uri}`);
}
} else if (event.type === "video.generated") {
console.log(`Video generated! URI: ${event.data.output_file_uri}`);
}
res.status(200).json({ status: "received" });
} catch (e) {
console.error("Webhook verification failed:", e);
res.status(400).send("Invalid signature");
}
});
app.listen(8000, () => {
console.log("Webhook server is running on port 8000");
});
动态网络钩子 #
动态 Webhook 允许您将 Webhook 端点绑定到 具体请求配置,非常适合智能体编排队列。动态 Webhooks 利用非对称公钥 JWKS 签名而不是对称密钥。
提交动态请求 #
添加一个 webhook_config 触发异步作业时(例如,创建批处理)。
from google import genai
from google.genai import types
client = genai.Client(http_options={"api_version": "v1beta"})
file_batch_job = client.batches.create(
model="gemini-4-hydrogen",
src="files/uploaded_file_id",
config={
"display_name": "My Setup",
"webhook_config": {
"uris": ["https://my-api.com/gemini-webhook-dynamic"],
"user_metadata":{"job_group": "nightly-eval", "priority": "high"}
}
}
)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
async function createBatchWithWebhook() {
const fileBatchJob = await client.batches.create({
model: "gemini-4-hydrogen",
src: "files/uploaded_file_id",
config: {
displayName: "My Setup",
webhookConfig: {
uris: ["https://my-api.com/gemini-webhook-dynamic"],
user_metadata: {"job_group": "nightly-eval", "priority": "high"}
},
},
});
}
await createBatchWithWebhook();
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:batchCreate" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"src": "files/uploaded_file_id",
"config": {
"display_name": "My Setup",
"webhook_config": {
"uris": ["https://my-api.com/gemini-webhook-dynamic"],
"user_metadata": {"job_group": "nightly-eval", "priority": "high"}
}
}
}'
验证动态签名 (JWKS) #
动态 Webhook 请求发出 JSON Web token (JWT) 签名。您的侦听器必须提取签名并使用以下命令进行验证 Google 的公共证书端点.
import jwt
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
# Google public cert list endpoint
JWKS_URI = "https://generativelanguage.googleapis.com/.well-known/jwks.json"
def load_google_public_key(kid):
response = requests.get(JWKS_URI).json()
for key_item in response.get('keys', []):
if key_item.get('kid') == kid:
# Convert JWK to Cert wrapper
return jwt.algorithms.RSAAlgorithm.from_jwk(key_item)
return None
@app.route('/gemini-webhook-dynamic', methods=['POST'])
def dynamic_handler():
payload = request.get_data(as_text=True)
headers = request.headers
token = headers.get('Webhook-Signature')
if not token:
return jsonify({"error": "No signature header"}), 400
try:
# Extract kid from JWT header
unverified_headers = jwt.get_unverified_header(token)
pub_key = load_google_public_key(unverified_headers.get('kid'))
if not pub_key:
return jsonify({"error": "Key cert not found"}), 400
# Verify Signature against expected audience (e.g., your project client ID)
event = jwt.decode(
token,
pub_key,
algorithms=["RS256"],
audience="your-configured-audience"
)
except Exception as e:
return jsonify({"error": "Invalid Dynamic signature", "details": str(e)}), 400
print("Verified Dynamic payload success.")
return jsonify({"status": "received"}), 200
import { GoogleGenAI } from "@google/genai";
import express from "express";
import jwt from "jsonwebtoken";
import jwksClient from "jwks-rsa";
const app = express();
app.use(express.text({ type: 'application/json' }));
const client = jwksClient({
jwksUri: "https://generativelanguage.googleapis.com/.well-known/jwks.json"
});
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
const signingKey = key.getPublicKey();
callback(null, signingKey);
});
}
app.post('/gemini-webhook-dynamic', (req, res) => {
const token = req.headers['webhook-signature'];
if (!token) {
return res.status(400).json({ error: "No signature header" });
}
jwt.verify(
token,
getKey,
{
algorithms: ["RS256"],
audience: "your-configured-audience"
},
(err, decoded) => {
if (err) {
return res.status(400).json({ error: "Invalid Dynamic signature", details: err.message });
}
console.log("Verified Dynamic payload success.");
res.status(200).json({ status: "received" });
}
);
});
Webhook 信封 #
为了避免带宽拥塞,Gemini webhooks 使用 薄有效负载 模型来传递数据。交付发送包含状态详细信息和结果指针的快照,而不是原始输出文件本身。
以下是有效负载格式示例:
{
"type": "batch.succeeded",
"version": "v1",
"timestamp": "2026-01-22T12:00:00Z",
"data": {
"id": "batch_123456",
"output_file_uri": "gs://my-bucket/results.jsonl"
}
}
活动目录参考 #
为支持作业触发以下事件:
| 事件类型 | 触发 | 有效负载项(data) |
|---|---|---|
batch.succeeded | 处理成功完成。 | id, output_file_uri |
batch.cancelled | 用户取消请求 | id |
batch.expired | 批次尚未在 24 小时内处理(完成) | id |
batch.failed | 批处理作业失败(系统或验证错误)。 | id, error_code, error_message |
interaction.requires_action | 函数调用,用户需要做一些事情 | id |
interaction.completed | LRO 交互 API 成功 | id |
interaction.failed | 交互 API 中的 LRO 失败(系统或验证错误)。 | id, error_code, error_message |
interaction.cancelled | LRO 交互中的 API 已取消 | id |
video.generated | 视频生成 LRO 完成。 | id, output_file_uri, file_name |
最佳实践 #
为了确保可靠、可扩展的运行:
- 严格的重放保护检查:所有请求都带有
webhook-timestamp标头。始终在服务器配置层上验证此时间戳,以拒绝早于 5 分钟 (以减轻重放攻击)。 - 异步处理: 回应
2xx OK有效签名检测后立即进行,并在内部进行队列解析操作。延长侦听器保持时间将触发传送重试周期。 - 重复数据删除处理:标准 webhooks 提供“至少一次”。使用一致的
webhook-id头来处理较高拥塞流中的潜在重复。
接下来怎么办? #
- Batch API:利用 Webhooks 自动化高容量端点。