对于初始测试,您可以对 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~/.bashrcopen~/.bashrc
接下来,您需要添加以下导出命令来设置 API 密钥:
exportGEMINI_API_KEY=<YOUR_API_KEY_HERE>
保存文件后,运行以下命令以应用更改:
source~/.bashrc
macOS - Zsh
Zsh 是一种常见的 Linux 和 macOS 终端配置。您可以运行以下命令,检查是否有相应的配置文件:
~/.zshrc
如果响应为“No such file or directory”,您需要创建此文件,并通过运行以下命令打开该文件,或使用 bash:
touch~/.zshrcopen~/.zshrc
接下来,您需要添加以下导出命令来设置 API 密钥:
exportGEMINI_API_KEY=<YOUR_API_KEY_HERE>
保存文件后,运行以下命令以应用更改:
source~/.zshrc
Windows
在系统设置中搜索“环境变量”
修改“用户变量”(针对当前用户)或“系统变量”(针对所有用户 - 请谨慎使用)。
创建变量并添加 export GEMINI_API_KEY=your_key_here
应用更改
显式提供 API 密钥
在某些情况下,您可能需要明确提供 API 密钥。例如:
您要进行简单的 API 调用,并且希望对 API 密钥进行硬编码。
您希望进行明确控制,而不必依赖 Gemini API 库自动发现环境变量
您使用的是不支持环境变量的环境(例如 Web),或者您正在进行 REST 调用。
以下示例展示了如何显式提供 API 密钥:
Python
fromgoogleimportgenaiclient=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";constai=newGoogleGenAI({apiKey:"YOUR_API_KEY"});asyncfunctionmain(){constresponse=awaitai.models.generateContent({model:"gemini-2.5-flash",contents:"Explain how AI works in a few words",});console.log(response.text);}main();
Go
packagemainimport("context""fmt""log""google.golang.org/genai")funcmain(){ctx:=context.Background()client,err:=genai.NewClient(ctx,&genai.ClientConfig{APIKey:"YOUR_API_KEY",Backend:genai.BackendGeminiAPI,})iferr!=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,)iferr!=nil{log.Fatal(err)}fmt.Println(result.Text())}
Java
packagecom.example;importcom.google.genai.Client;importcom.google.genai.types.GenerateContentResponse;publicclassGenerateTextFromTextInput{publicstaticvoidmain(String[]args){Clientclient=Client.builder().apiKey("YOUR_API_KEY").build();GenerateContentResponseresponse=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'\-XPOST\-d'{ "contents": [ { "parts": [ { "text": "Explain how AI works in a few words" } ] } ] }'
确保 API 密钥的安全
请像对待密码一样对待 Gemini API 密钥。如果密钥泄露,其他人可以使用您项目的配额、产生费用(如果已启用结算),并访问您的私人数据(例如文件)。
严重安全规则
切勿将 API 密钥提交到源代码控制系统。请勿将 API 密钥签入 Git 等版本控制系统。
切勿在客户端公开 API 密钥。请勿在生产环境中的 Web 应用或移动应用中直接使用 API 密钥。客户端代码(包括我们的 JavaScript/TypeScript 库和 REST 调用)中的密钥可能会被提取。
最佳做法
使用带有 API 密钥的服务器端调用:使用 API 密钥的最安全方式是从服务器端应用调用 Gemini API,这样可以确保密钥的保密性。
使用临时令牌进行客户端访问(仅限 Live API):如需直接从客户端访问 Live API,您可以使用临时令牌。它们的安全风险较低,适合在生产环境中使用。如需了解详情,请参阅临时令牌指南。
考虑为密钥添加限制:您可以通过添加 API 密钥限制来限制密钥的权限。这样可以最大限度地减少密钥泄露时可能造成的损害。
[[["易于理解","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"]],["最后更新时间 (UTC):2025-08-22。"],[],[],null,["To use the Gemini API, you need an API key. You can create a key for free with a\nfew clicks in [Google AI Studio](https://aistudio.google.com/app/apikey).\n\nOnce you have an API key, you have the following options to connect to the\nGemini API:\n\n- [Setting your API key as an environment variable](#set-api-env-var)\n- [Providing your API key explicitly](#provide-api-key-explicitly)\n\nFor initial testing, you can hard code an API key, but this should only be\ntemporary since it's not secure. You can find examples for hard coding the API\nkey in [Providing API key explicitly](#provide-api-key-explicitly) section.\n\nSetting API key as environment variable\n\nIf you set the environment variable `GEMINI_API_KEY` or `GOOGLE_API_KEY`, the\nAPI key will automatically be picked up by the client when using one of the\n[Gemini API libraries](/gemini-api/docs/libraries). It's recommended that you\nset only one of those variables, but if both are set, `GOOGLE_API_KEY` takes\nprecedence.\n\nIf you're using the REST API, or JavaScript on the browser, you will need to\nprovide the API key explicitly.\n\nHere is how you can set your API key locally as the environment variable\n`GEMINI_API_KEY` with different operating systems. \n\nLinux/macOS - Bash\n\nBash is a common Linux and macOS terminal configuration. You can check if\nyou have a configuration file for it by running the following command: \n\n ~/.bashrc\n\nIf the response is \"No such file or directory\", you will need to create this\nfile and open it by running the following commands, or use `zsh`: \n\n touch ~/.bashrc\n open ~/.bashrc\n\nNext, you need to set your API key by adding the following export command: \n\n export GEMINI_API_KEY=\u003cYOUR_API_KEY_HERE\u003e\n\nAfter saving the file, apply the changes by running: \n\n source ~/.bashrc\n\nmacOS - Zsh\n\nZsh is a common Linux and macOS terminal configuration. You can check if\nyou have a configuration file for it by running the following command: \n\n ~/.zshrc\n\nIf the response is \"No such file or directory\", you will need to create this\nfile and open it by running the following commands, or use `bash`: \n\n touch ~/.zshrc\n open ~/.zshrc\n\nNext, you need to set your API key by adding the following export command: \n\n export GEMINI_API_KEY=\u003cYOUR_API_KEY_HERE\u003e\n\nAfter saving the file, apply the changes by running: \n\n source ~/.zshrc\n\nWindows\n\n1. Search for \"Environment Variables\" in the system settings\n2. Edit either \"User variables\" (for current user) or \"System variables\" (for all users - use with caution).\n3. Create the variable and add `export GEMINI_API_KEY=your_key_here`\n4. Apply the changes\n\nProviding API key explicitly\n\nIn some cases, you may want to explicitly provide an API key. For example:\n\n- You're doing a simple API call and prefer hard coding the API key.\n- You want explicit control without having to rely on automatic discovery of environment variables by the Gemini API libraries\n- You're using an environment where environment variables are not supported (e.g web) or you are making REST calls.\n\nBelow are examples for how you can provide an API key explicitly: \n\nPython \n\n from google import genai\n\n client = genai.Client(api_key=\"\u003cvar translate=\"no\"\u003eYOUR_API_KEY\u003c/var\u003e\")\n\n response = client.models.generate_content(\n model=\"gemini-2.5-flash\", contents=\"Explain how AI works in a few words\"\n )\n print(response.text)\n\nJavaScript \n\n import { GoogleGenAI } from \"@google/genai\";\n\n const ai = new GoogleGenAI({ apiKey: \"\u003cvar translate=\"no\"\u003eYOUR_API_KEY\u003c/var\u003e\" });\n\n async function main() {\n const response = await ai.models.generateContent({\n model: \"gemini-2.5-flash\",\n contents: \"Explain how AI works in a few words\",\n });\n console.log(response.text);\n }\n\n main();\n\nGo \n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"log\"\n \"google.golang.org/genai\"\n )\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, &genai.ClientConfig{\n APIKey: \"\u003cvar translate=\"no\"\u003eYOUR_API_KEY\u003c/var\u003e\",\n Backend: genai.BackendGeminiAPI,\n })\n if err != nil {\n log.Fatal(err)\n }\n\n result, err := client.Models.GenerateContent(\n ctx,\n \"gemini-2.5-flash\",\n genai.Text(\"Explain how AI works in a few words\"),\n nil,\n )\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(result.Text())\n }\n\nJava \n\n package com.example;\n\n import com.google.genai.Client;\n import com.google.genai.types.GenerateContentResponse;\n\n public class GenerateTextFromTextInput {\n public static void main(String[] args) {\n Client client = Client.builder().apiKey(\"\u003cvar translate=\"no\"\u003eYOUR_API_KEY\u003c/var\u003e\").build();\n\n GenerateContentResponse response =\n client.models.generateContent(\n \"gemini-2.5-flash\",\n \"Explain how AI works in a few words\",\n null);\n\n System.out.println(response.text());\n }\n }\n\nREST \n\n curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$\u003cvar translate=\"no\"\u003eYOUR_API_KEY\u003c/var\u003e\" \\\n -H 'Content-Type: application/json' \\\n -X POST \\\n -d '{\n \"contents\": [\n {\n \"parts\": [\n {\n \"text\": \"Explain how AI works in a few words\"\n }\n ]\n }\n ]\n }'\n\nKeep your API key secure\n\nTreat your Gemini API key like a password. If compromised, others can use your\nproject's quota, incur charges (if billing is enabled), and access your\nprivate data, such as files.\n\nCritical security rules\n\n- **Never commit API keys to source control.** Do not check your API key into version control systems like Git.\n\n- **Never expose API keys on the client-side.** Do not use your API key directly\n in web or mobile apps in production. Keys in client-side code\n (including our JavaScript/TypeScript libraries and REST calls) can be\n extracted.\n\nBest practices\n\n- **Use server-side calls with API keys** The most secure way to use your API\n key is to call the Gemini API from a server-side application where the key\n can be kept confidential.\n\n- **Use ephemeral tokens for client-side access (Live API only):** For direct\n client-side access to the Live API, you can use ephemeral tokens. They come with\n lower security risks and can be suitable for production use. Review\n [ephemeral tokens](/gemini-api/docs/ephemeral-tokens) guide for more information.\n\n- **Consider adding restrictions to your key:** You can limit a key's permissions\n by adding [API key restrictions](https://cloud.google.com/api-keys/docs/add-restrictions-api-keys#add-api-restrictions).\n This minimizes the potential damage if the key is ever leaked.\n\nFor some general best practices, you can also review this\n[support article](https://support.google.com/googleapi/answer/6310037)."]]