Webhook

Webhook memungkinkan Gemini API mengirim notifikasi real-time ke server Anda saat Operasi Asinkron atau Operasi yang Berjalan Lama (LRO) selesai. Hal ini menggantikan kebutuhan untuk melakukan polling API guna mendapatkan update status, sehingga mengurangi latensi dan overhead.

Webhook tersedia untuk operasi seperti Tugas batch, Interaksi, dan pembuatan video.

Cara kerjanya

Daripada melakukan polling GET /operations berulang kali untuk memeriksa apakah tugas telah selesai, Anda dapat mengonfigurasi Webhook Gemini API untuk mengirim permintaan POST HTTP ke URL pemroses Anda segera setelah pemicu peristiwa.

Gemini API mendukung dua cara untuk mengonfigurasi webhook:

  • Webhook statis: Endpoint tingkat project yang dikonfigurasi dengan Gemini WebhookService API. Baik untuk integrasi global (misalnya, memberi tahu Slack, menyinkronkan database, dll.).
  • Webhook dinamis: Penggantian tingkat permintaan yang meneruskan URL webhook dalam payload konfigurasi panggilan tugas tertentu. Ideal untuk merutekan tugas tertentu ke endpoint khusus.

Webhook statis

Webhook statis terdaftar untuk seluruh project dan dipicu untuk peristiwa yang cocok.

Membuat webhook

Anda dapat membuat endpoint menggunakan SDK atau REST API.

PENTING: Saat membuat webhook, API hanya menampilkan secret penandatanganan satu kali. Anda harus menyimpannya dengan aman (misalnya, dalam variabel lingkungan) untuk memverifikasi tanda tangan nanti. Jika kehilangan secret penandatanganan, Anda harus merotasinya.

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"]
  }'

Untuk mengetahui detail tentang cara menyiapkan server untuk menerima data, lihat bagian Menangani permintaan webhook.

Mendapatkan webhook

Ambil detail tentang webhook tertentu berdasarkan nama resource-nya.

Python

from google import genai

client = genai.Client()

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

print(f"Webhook: {webhook.name}")
print(f"URI: {webhook.uri}")
print(f"Events: {webhook.subscribed_events}")

JavaScript

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

const client = new GoogleGenAI(); // 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}`);
}

getWebhook();

REST

curl -X GET \
  "https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Mencantumkan webhook

Cantumkan semua webhook yang dikonfigurasi untuk project saat ini, dengan penomoran halaman opsional.

Python

from google import genai

client = genai.Client()

webhooks = client.webhooks.list()

for wh in webhooks:
    print(f"{wh.id}: {wh.name} -> {wh.uri}")

JavaScript

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

const client = new GoogleGenAI();

async function listWebhooks() {
  const webhooks = await client.webhooks.list();

  for (const wh of webhooks) {
    console.log(`${wh.id}: ${wh.name} -> ${wh.uri}`);
  }
}

listWebhooks();

REST

curl -X GET \
  "https://generativelanguage.googleapis.com/v1/webhooks" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Memperbarui webhook

Perbarui properti webhook yang ada seperti nama tampilan, URI target, atau peristiwa yang diikuti.

Python

from google import genai

client = genai.Client()

updated_webhook = client.webhooks.update(
    id="<your_webhook_id>",
    subscribed_events=["batch.succeeded", "batch.failed", "batch.cancelled"],
)

print(f"Updated webhook: {updated_webhook.name}")

JavaScript

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

const client = new GoogleGenAI();

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}`);
}

updateWebhook();

REST

curl -X PATCH \
  "https://generativelanguage.googleapis.com/v1/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"]
  }'

Menghapus webhook

Hapus endpoint webhook dari project. Tindakan ini akan menghentikan pengiriman peristiwa di masa mendatang ke endpoint tersebut.

Python

from google import genai

client = genai.Client()

client.webhooks.delete(id="<your_webhook_id>")

print("Webhook deleted.")

JavaScript

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

const client = new GoogleGenAI();

async function deleteWebhook() {
  await client.webhooks.delete("<your_webhook_id>");

  console.log("Webhook deleted.");
}

deleteWebhook();

REST

curl -X DELETE \
  "https://generativelanguage.googleapis.com/v1/webhooks/<your_webhook_id>" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Merotasi secret penandatanganan

Rotasi secret penandatanganan untuk webhook. Anda dapat mengonfigurasi apakah secret yang sebelumnya aktif akan dicabut segera atau setelah masa tenggang 24 jam.

PENTING: Secret penandatanganan baru hanya ditampilkan satu kali pada waktu rotasi time. Simpan dengan aman sebelum memperbarui logika verifikasi Anda.

Python

from google import genai
from google.genai import types

client = genai.Client()

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.")

JavaScript

import {