Gemini API 快速入门

本快速入门将向您介绍如何安装我们的并发出您的第一个 Gemini API 请求。

准备工作

使用 Gemini API 需要 API 密钥,您可以免费创建一个 API 密钥以开始使用。

创建 Gemini API 密钥

安装 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>

C#

使用 dotnet add 命令在模块目录中安装 googleapis/go-genai

dotnet add package Google.GenAI

Apps 脚本

  1. 如需创建新的 Apps 脚本项目,请前往 script.new
  2. 点击未命名项目
  3. 将 Apps 脚本项目重命名为 AI Studio,然后点击重命名
  4. 设置 API 密钥
    1. 点击左侧的项目设置 项目设置图标
    2. 脚本属性下,点击添加脚本属性
    3. 对于属性,输入键名称:GEMINI_API_KEY
    4. 字段中,输入 API 密钥的值。
    5. 点击保存脚本属性
  5. 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-3-flash-preview", 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-3-flash-preview",
    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-3-flash-preview",
        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-3-flash-preview",
            "Explain how AI works in a few words",
            null);

    System.out.println(response.text());
  }
}

C#

using System.Threading.Tasks;
using Google.GenAI;
using Google.GenAI.Types;

public class GenerateContentSimpleText {
  public static async Task main() {
    // The client gets the API key from the environment variable `GEMINI_API_KEY`.
    var client = new Client();
    var response = await client.Models.GenerateContentAsync(
      model: "gemini-3-flash-preview", contents: "Explain how AI works in a few words"
    );
    Console.WriteLine(response.Candidates[0].Content.Parts[0].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-3-flash-preview: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-3-flash-preview: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 的实际应用: