如要使用 Gemini API,您需要 API 金鑰。在 Google AI Studio 中按幾下滑鼠,即可免費建立金鑰。

取得 API 金鑰後,您可以透過下列方式連線至 Gemini API:

  • 將 API 金鑰設為環境變數
  • 明確提供 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

    1. 在系統設定中搜尋「環境變數」
    2. 編輯「使用者變數」(適用於目前使用者) 或「系統變數」(適用於所有使用者,請謹慎使用)。
    3. 建立變數並新增 export GEMINI_API_KEY=your_key_here
    4. 明確提供 API 金鑰

      在某些情況下,您可能需要明確提供 API 金鑰。例如:

    5. 您要進行簡單的 API 呼叫,且偏好對 API 金鑰進行硬式編碼。
    6. 您希望明確控管,而不必依賴 Gemini API 程式庫自動探索環境變數
    7. 您使用的環境不支援環境變數 (例如網頁),或是您正在發出 REST 呼叫。
    8. 以下範例說明如何明確提供 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 金鑰視為密碼,如果遭到盜用,他人就能使用專案配額、產生費用 (如果已啟用帳單功能),以及存取您的私人資料 (例如檔案)。

      重大安全性規則

    9. 切勿將 API 金鑰提交至原始碼控管系統。請勿在 Git 等版本管控系統中登錄 API 金鑰。

    10. 請勿在用戶端公開 API 金鑰。請勿直接在正式版網頁或行動應用程式中使用 API 金鑰。用戶端程式碼中的金鑰 (包括我們的 JavaScript/TypeScript 程式庫和 REST 呼叫) 可能會遭到擷取。

    11. 使用 API 金鑰進行伺服器端呼叫:如要以最安全的方式使用 API 金鑰,請從伺服器端應用程式呼叫 Gemini API,這樣就能確保金鑰機密性。

    12. 使用臨時權杖進行用戶端存取 (僅限 Live API):如要直接從用戶端存取 Live API,可以使用臨時權杖。這些版本安全性風險較低,適合用於實際工作環境。詳情請參閱「臨時權杖」指南。

    13. 考慮為金鑰新增限制:您可以新增 API 金鑰限制,藉此限制金鑰的權限。這麼做可將金鑰外洩時造成的潛在損害降到最低。

    14. 如需一般最佳做法,請參閱這篇支援文章

      除非另有註明,否則本頁面中的內容是採用創用 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 (世界標準時間)。"],[],[]]