本快速入门将向您介绍如何安装我们的库并发出您的第一个 Gemini API 请求。
准备工作
您需要 Gemini API 密钥。如果您还没有 API 密钥,可以在 Google AI Studio 中免费获取。
安装 Google GenAI SDK
Python
使用 Python 3.9 及更高版本,通过以下 pip 命令安装 google-genai 软件包:
pip install -q -U google-genai
JavaScript
使用 Node.js v18 及更高版本,通过以下 npm 命令安装 Google Gen AI SDK(适用于 TypeScript 和 JavaScript):
npm install @google/genai
Go
使用 go get 命令在模块目录中安装 google.golang.org/genai:
go get google.golang.org/genai
Java
如果您使用的是 Maven,则可以通过向依赖项添加以下内容来安装 google-genai:
<dependencies>
  <dependency>
    <groupId>com.google.genai</groupId>
    <artifactId>google-genai</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>
Apps 脚本
- 如需创建新的 Apps 脚本项目,请前往 script.new。
- 点击无标题项目。
- 将 Apps 脚本项目重命名为 AI Studio,然后点击重命名。
- 设置 API 密钥 
- 点击左侧的项目设置 。 
- 在脚本属性下,点击添加脚本属性。
- 对于属性,输入键名称:GEMINI_API_KEY。
- 在值字段中,输入 API 密钥的值。
- 点击保存脚本属性。
 
- 点击左侧的项目设置 
- 将 Code.gs文件内容替换为以下代码:
提交第一个请求
以下示例使用 generateContent 方法,通过 Gemini 2.5 Flash 模型向 Gemini API 发送请求。
如果您将 API 密钥设置为环境变量 GEMINI_API_KEY,那么在使用 Gemini API 库时,客户端会自动获取该密钥。否则,您需要在初始化客户端时将 API 密钥作为实参传递。
请注意,Gemini API 文档中的所有代码示例都假定您已设置环境变量 GEMINI_API_KEY。
Python
from google import genai
# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()
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";
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});
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()
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    client, err := genai.NewClient(ctx, nil)
    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) {
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    Client client = new Client();
    GenerateContentResponse response =
        client.models.generateContent(
            "gemini-2.5-flash",
            "Explain how AI works in a few words",
            null);
    System.out.println(response.text());
  }
}
Apps 脚本
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };
  const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
  const options = {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      'x-goog-api-key': apiKey,
    },
    payload: JSON.stringify(payload)
  };
  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'
后续步骤
现在,您已发出第一个 API 请求,不妨探索以下指南,了解 Gemini 的实际应用: