Repository Public
1To use the Gemini API, you must authenticate your requests. You can2authenticate using a standard or authorization API key.34[Create or view a Gemini API Key](https://aistudio.google.com/apikey)56## API key types: standard versus authorization78API keys provide access to the Gemini API, but their security characteristics9differ. The Gemini API is transitioning from standard API keys to authorization10keys to improve security:1112- **Standard API keys**: Associate requests with a Google Cloud project for billing and quota purposes. Standard keys don't identify a caller, which limits the granularity of permissions and access control they can support.13- **Authorization (auth) keys**: Bound directly to a Google Cloud service account. When you use an authorization key, your requests are processed under the identity of that bound service account, enabling granular access control. Authorization keys are restricted to the Generative Language API (Gemini API) by default and provide fast-acting leaked key enforcement that quickly stops the usage of leaked keys detected by our systems.1415To ensure secure usage, Gemini API will move from standard keys to auth keys:1617- **Auth keys default**: Starting May 28, 2026, all new API keys created in Google AI Studio are automatically created as auth keys.18- **Unrestricted keys rejected** : The Gemini API rejects requests from **unrestricted standard keys**. Standard API keys that have explicit restrictions applied continue to work. This restriction prevents the unauthorized use of keys that might be shared publicly or linked to other services.19- **On September 2026** : the Gemini API will reject requests from **standard20 keys** . You must [migrate to auth keys](https://ai.google.dev/gemini-api/docs/generate-content/api-key#migrate-to-auth-key) before this date to avoid service interruption. Make sure to migrate to auth keys before September 2026.2122> [!NOTE]23> **Note:** Requests authenticated by authorization keys are not recorded in Google Cloud service account usage metrics.2425## Managing API keys in Google AI Studio2627You can manage your projects and keys directly in [Google AI Studio](https://aistudio.google.com/apikey).2829### Google Cloud projects3031Every Gemini API key is associated with a [Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).32Google Cloud projects manage billing, collaborators, and permissions. Google AI33Studio provides a lightweight interface to access these projects.3435- **Default project** : If you are a new user, Google AI Studio automatically creates a default Google Cloud project and API key after you accept the Terms of Service. You can rename this project by navigating to the **Projects** view in your dashboard.36- **Existing projects**: If you already have a Google Cloud account, AI Studio does not create a default project. Instead, you must import your existing projects.3738### Importing projects3940By default, Google AI Studio does not display all of your Google Cloud41projects. You must import the projects you want to use:42431. Go to [Google AI Studio](https://aistudio.google.com).442. Open the **Dashboard** from the left panel and select **Projects**.453. Click the **Import projects** button.464. Search for and select the Google Cloud project you want to import, then click **Import**.475. Once imported, navigate to the **API Keys** page in the dashboard to create a key in that project.4849### Troubleshooting key creation permissions5051If the **Create API key** button is unavailable and displays the message:52*"You do not have permission to create a key in this project"*, you lack the53required IAM permissions.5455Ask your Google Cloud project or organization administrator to grant you a role56containing the following permissions (such as Project Editor):5758- `resourcemanager.projects.get`: Allows AI Studio to verify the project.59- `apikeys.keys.create`: Allows key generation.60- `serviceusage.services.enable`: Ensures the Generative Language API is enabled.61- `iam.serviceAccounts.create`: Required to create the linked service account.62- `iam.serviceAccountApiKeyBindings.create`: Binds the service account to the API key.6364If you cannot get administrative access, you can create a new Google Cloud65project that is not associated with an organization to generate your keys.6667## Setting up your environment6869Once you have a key, configure your environment to use it securely in your70applications.7172### Use environment variables (recommended)7374Set the environment variable `GEMINI_API_KEY` or `GOOGLE_API_KEY`. The Gemini75API client libraries automatically detect and use these variables. If both are76set, `GOOGLE_API_KEY` takes precedence.7778Select your operating system to set the variable:7980### Linux/macOS - Bash8182Verify if you have a bash configuration file:8384 ~/.bashrc8586If not, create one and open it:8788 touch ~/.bashrc && open ~/.bashrc8990Add the export command at the end of the file:9192 export GEMINI_API_KEY=<YOUR_API_KEY_HERE>9394Save the file, then apply the changes:9596 source ~/.bashrc9798### macOS - Zsh99100Verify if you have a zsh configuration file:101102 ~/.zshrc103104If not, create one and open it:105106 touch ~/.zshrc && open ~/.zshrc107108Add the export command:109110 export GEMINI_API_KEY=<YOUR_API_KEY_HERE>111112Save the file, then apply the changes:113114 source ~/.zshrc115116### Windows1171181. Search for "Environment Variables" in the Windows search bar.1192. Click **Environment Variables** in the System Properties dialog.1203. Under **User variables** or **System variables** , click **New...**.1214. Set the variable name to `GEMINI_API_KEY` and the value to your API key.1225. Click **OK** to save. Open a new terminal session to load the variable.123124### Provide the API key explicitly in code125126You can pass the API key explicitly when initializing the client. Only do this127if you cannot use environment variables.128129### Python130131 from google import genai132133 client = genai.Client(api_key="YOUR_API_KEY")134135 response = client.models.generate_content(136 model="gemini-3.8-flash",137 contents="Explain how AI works in a few words"138 )139 print(response.text)140141### JavaScript142143 import { GoogleGenAI } from "@google/genai";144145 const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });146147 async function main() {148 const response = await ai.models.generateContent({149 model: "gemini-3.8-flash",150 contents: "Explain how AI works in a few words",151 });152 console.log(response.text);153 }154155 main();156157### Go158159 package main160161 import (162 "context"163 "fmt"164 "log"165 "google.golang.org/genai"166 )167168 func main() {169 ctx := context.Background()170 client, err := genai.NewClient(ctx, &genai.ClientConfig{171 APIKey: "YOUR_API_KEY",172 Backend: genai.BackendGeminiAPI,173 })174 if err != nil {175 log.Fatal(err)176 }177178 result, err := client.Models.GenerateContent(179 ctx,180 "gemini-3.8-flash",181 genai.Text("Explain how AI works in a few words"),182 nil,183 )184 if err != nil {185 log.Fatal(err)186 }187 fmt.Println(result.Text())188 }189190### Java191192 package com.example;193194 import com.google.genai.Client;195 import com.google.genai.types.GenerateContentResponse;196197 public class GenerateTextFromTextInput {198 public static void main(String[] args) {199 Client client = Client.builder().apiKey("YOUR_API_KEY").build();200201 GenerateContentResponse response =202 client.models.generateContent(203 "gemini-3.8-flash",204 "Explain how AI works in a few words",205 null);206207 System.out.println(response.text());208 }209 }210211### REST212213 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" -H 'Content-Type: application/json' -H "x-goog-api-key: YOUR_API_KEY" -X POST -d '{214 "contents": [215 {216 "parts": [217 {218 "text": "Explain how AI works in a few words"219 }220 ]221 }222 ]223 }'224225## Security and secret management226227Treat your Gemini API key like a password. If compromised, others can consume228your project's quota, incur unexpected billing charges, and access private229resources.230231### Critical security rules232233- **Keep keys confidential**: Never check API keys into source control systems like Git.234- **Never expose keys client-side in production**: Do not hardcode API keys directly in web or mobile apps. Keys compiled in client-side code can be extracted by users. To secure client-side apps, run a backend proxy server to make the actual API calls.235236### Secret management best practices237238- **Environment variables**: Read keys from environment variables rather than configuration files.239- **Secret Manager** : For production, store your keys in a secure secret store such as [Google Cloud Secret Manager](https://cloud.google.com/secret-manager).240- **Billing alerts**: Set up billing alerts in the Google Cloud Console to notify you if usage or costs spike.241242### Leak response checklist243244If you suspect your API key has been leaked:2452461. **Generate a new key**: Create a replacement key in Google AI Studio or the Cloud Console.2472. **Update your application**: Deploy your code using the new key.2483. **Disable or delete the compromised key**: Disable the leaked key in the Cloud Console once the new key is verified. Do not delete the old key until the new key is fully active to avoid application downtime.2494. **Audit usage**: Check billing logs and API usage in the Google Cloud Console to identify unauthorized activity.250251## Restricting and securing your keys252253Adding restrictions to your API keys minimizes the potential damage if a key is254compromised.255256### Apply request origin restrictions257258Origin restrictions limit which IP addresses, websites, or applications can use259your key.2602611. Go to the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials).2622. Select your project, and click the name of the API key you want to restrict.2633. Under **Application restrictions** , select **IP addresses** (or the appropriate restriction type for your environment).2644. Specify the allowed IP addresses or ranges, then click **Save**.265266### Securing unrestricted standard API keys267268To continue using the Gemini API, you must secure any unrestricted keys.269270#### Restrict the key to the Gemini API only via AI Studio271272If you only use the key for the Gemini API, secure it directly in AI Studio:2732741. On the **API Keys** page in [Google AI Studio](https://aistudio.google.com/api-keys), locate keys marked with the **Unrestricted** label.2752. Hover over the label and click **Add restrictions** in the dialog.2763. Select **Restrict to Gemini API only**.2774. Click **Restrict key** to confirm.278279> [!NOTE]280> **Note:** To restrict an API key, you must have the `apikeys.keys.update` permission on the associated Google Cloud project. This permission is included in roles like **API Keys Admin** or **Editor**.281282#### Restrict the key for other services via Google Cloud Console283284If the key is shared with other Google APIs (not recommended), restrict it in285the Cloud Console. **Note: Gemini API requests using this key will fail after286these restrictions are applied.**2872881. Visit the [Google Cloud Console Credentials page](https://console.cloud.google.com/apis/credentials).2892. Select the project and the API key.2903. Under **API restrictions** , select **Restrict key**.2914. From the drop-down, select the APIs you want this key to access. Do not select the **Generative Language API**.2925. Click **Save**. Create a separate, restricted key in AI Studio to continue using the Gemini API.293294### Blocked dormant keys295296Starting May 7, 2026, the Gemini API blocks unrestricted API keys that have297been dormant for an extended period. These keys show a **Blocked** tag in AI298Studio. You must generate a new key or use an existing restricted key to299continue.300301## Migrate to an auth key302303Follow these steps to create a new auth API key and update your applications:3043051. Go to the [AI Studio API Keys page](https://aistudio.google.com/api-keys).3062. Check the **Key Type** column to identify any keys listed as **Standard**.3073. Click **Create API key** to generate a new key. All new keys created in AI Studio are automatically created as auth keys.3084. Copy the new auth API key.3095. Update your application code, environment variables, and any deployment configurations to use the new auth API key.3106. Test your application to confirm it works correctly with the new key.3117. Once verified, delete or revoke your old traffic key to prevent misuse.312313> [!NOTE]314> **Note:** If you don't see your keys, you may need to import your Cloud projects into AI Studio. Refer to the [import projects](https://ai.google.dev/gemini-api/docs/generate-content/api-key#import-projects) section for instructions.315316## Limitations317318Google AI Studio imposes the following project and key management limitations:319320- You can create a maximum of 10 projects at a time from the Google AI Studio **Projects** page.321- The **API keys** and **Projects** pages display a maximum of 100 keys and 50 projects.322- Only API keys that are unrestricted or restricted specifically to the Generative Language API (Gemini API) are displayed.323324For advanced project management or to modify keys with other restrictions, use325the [Google Cloud Console credentials page](https://console.cloud.google.com/apis/credentials).