from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
response = client.models.generate_content(
model="gemini-2.5-flash", contents="Explain how AI works in a few words"
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain how AI works in a few words",
console.log(response.text);
main();
Go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: "YOUR_API_KEY",
Backend: genai.BackendGeminiAPI,
if err != nil {
log.Fatal(err)
result, err := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("Explain how AI works in a few words"),
nil,
if err != nil {
log.Fatal(err)
fmt.Println(result.Text())
Java
package com.example;
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateTextFromTextInput {
public static void main(String[] args) {
Client client = Client.builder().apiKey("YOUR_API_KEY").build();
GenerateContentResponse response =
client.models.generateContent(
"gemini-2.5-flash",
"Explain how AI works in a few words",
null);
System.out.println(response.text());
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$YOUR_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
"parts": [
"text": "Explain how AI works in a few words"
妥善保管 API 金鑰
請將 Gemini API 金鑰視為密碼,如果遭到盜用,他人就能使用專案配額、產生費用 (如果已啟用帳單功能),以及存取您的私人資料 (例如檔案)。
重大安全性規則
切勿將 API 金鑰提交至原始碼控管系統。請勿在 Git 等版本管控系統中登錄 API 金鑰。
請勿在用戶端公開 API 金鑰。請勿直接在正式版網頁或行動應用程式中使用 API 金鑰。用戶端程式碼中的金鑰 (包括我們的 JavaScript/TypeScript 程式庫和 REST 呼叫) 可能會遭到擷取。
使用 API 金鑰進行伺服器端呼叫:如要以最安全的方式使用 API 金鑰,請從伺服器端應用程式呼叫 Gemini API,這樣就能確保金鑰機密性。
使用臨時權杖進行用戶端存取 (僅限 Live API):如要直接從用戶端存取 Live API,可以使用臨時權杖。這些版本安全性風險較低,適合用於實際工作環境。詳情請參閱「臨時權杖」指南。
考慮為金鑰新增限制:您可以新增 API 金鑰限制,藉此限制金鑰的權限。這麼做可將金鑰外洩時造成的潛在損害降到最低。
如需一般最佳做法,請參閱這篇支援文章。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-22 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-22 (世界標準時間)。"],[],[]]