如要使用 Gemini API,您需要 API 金鑰。在 Google AI Studio 中按幾下滑鼠,即可免費建立金鑰。
取得 API 金鑰後,您可以透過下列方式連線至 Gemini API:
進行初步測試時,您可以將 API 金鑰寫死在程式碼中,但這只是暫時做法,因為並不安全。如需以硬式編碼方式提供 API 金鑰的範例,請參閱「明確提供 API 金鑰」一節。
將 API 金鑰設為環境變數
如果您設定環境變數 GEMINI_API_KEY
或 GOOGLE_API_KEY
,使用 Gemini API 程式庫時,用戶端會自動擷取 API 金鑰。建議您只設定其中一個變數,但如果兩個都設定,系統會優先採用 GOOGLE_API_KEY
。
如果您使用 REST API 或瀏覽器上的 JavaScript,則必須明確提供 API 金鑰。
以下說明如何在不同作業系統中,將 API 金鑰在本機設為環境變數 GEMINI_API_KEY
。
Linux/macOS - Bash
Bash 是常見的 Linux 和 macOS 終端機設定。如要檢查是否有設定檔,請執行下列指令:
~/.bashrc
如果回應為「No such file or directory」,您需要建立這個檔案,並執行下列指令來開啟檔案,或使用 zsh
:
touch ~/.bashrc
open ~/.bashrc
接著,您需要新增下列匯出指令,設定 API 金鑰:
export GEMINI_API_KEY=<YOUR_API_KEY_HERE>
儲存檔案後,請執行下列指令來套用變更:
source ~/.bashrc
macOS - Zsh
Zsh 是常見的 Linux 和 macOS 終端機設定。如要檢查是否有設定檔,請執行下列指令:
~/.zshrc
如果回應為「No such file or directory」,您需要建立這個檔案,並執行下列指令來開啟檔案,或使用 bash
:
touch ~/.zshrc
open ~/.zshrc
接著,您需要新增下列匯出指令,設定 API 金鑰:
export GEMINI_API_KEY=<YOUR_API_KEY_HERE>
儲存檔案後,請執行下列指令來套用變更:
source ~/.zshrc
Windows
- 在系統設定中搜尋「環境變數」
- 編輯「使用者變數」(適用於目前使用者) 或「系統變數」(適用於所有使用者,請謹慎使用)。
- 建立變數並新增
export GEMINI_API_KEY=your_key_here
- 套用變更
明確提供 API 金鑰
在某些情況下,您可能需要明確提供 API 金鑰。例如:
- 您要進行簡單的 API 呼叫,並偏好對 API 金鑰進行硬式編碼。
- 您想要明確控制,而不必依賴 Gemini API 程式庫自動探索環境變數
- 您使用的環境不支援環境變數 (例如網頁),或是您正在發出 REST 呼叫。
以下範例說明如何明確提供 API 金鑰:
Python
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 金鑰限制,藉此限制金鑰的權限。這麼做可將金鑰外洩時造成的潛在損害降到最低。
如需一般最佳做法,請參閱這篇支援文章。