Gemini API 快速入门
本快速入门将介绍如何安装我们的库,以及如何使用 Interactions API 发出您的第一个 Gemini API 请求。
准备工作
使用 Gemini API 需要 API 密钥,您可以免费创建一个 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
提交第一个请求
以下示例使用 Interactions API 通过 Gemini 3 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()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain how AI works in a few words"
)
# Print the model's text response
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.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 interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Explain how AI works in a few words",
});
const modelStep = interaction.steps.find(s => s.type === 'model_output');
if (modelStep) {
for (const contentBlock of modelStep.content) {
if (contentBlock.type === 'text') console.log(contentBlock.text);
}
}
}
main();
REST
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": "Explain how AI works in a few words"
}'
后续步骤
现在,您已发出第一个 API 请求,不妨探索以下指南,了解 Gemini 的实际应用: