How to Get a Gemini API Key (and Use It Safely)
TL;DR
Get a Gemini API key in Google AI Studio, connect it in Python, JS or curl, and fix the usual 400, 403 and 429 errors.
Issuing the key takes about three minutes. Everything that goes wrong happens after that: the key lands in a project you did not mean to use, the free tier runs out sooner than expected, or the first request returns a 403 and you cannot tell whether the fault is the key, the request, or the account behind it.
I build content pipelines that call Gemini every day, and the pattern repeats. People are not stuck on the **Create API key** button. They are stuck on the status codes that follow it, and in most cases the key is not the culprit.
What a Gemini API key is, and when you need one
An API key is a string that starts with `AIzaSy…` and identifies your application to Google's servers. It tells the server which Google Cloud project the request belongs to, which quota to charge, and which billing account to bill.
That is the difference from the Gemini app in your browser. In the app, a human is in the loop: you open a tab, type a prompt, copy the answer. A key is for the cases where nobody is sitting there — a script, a Telegram bot, a CMS plugin, a nightly job that writes fifty articles. Ten one-off prompts belong in the browser; anything scheduled, repeated, or embedded in your product needs a key.
Know one thing up front: every key is tied to a Google Cloud project, and that project owns the billing and the quota. Keys from two different projects behave like two separate accounts.
Getting the key in Google AI Studio
The key is issued at [aistudio.google.com](https://aistudio.google.com/apikey), and a regular Google account is enough — there is no separate developer registration.
**1. Sign in and find your project.** If you are new to AI Studio, Google creates a default Cloud project and a first key as soon as you accept the terms. If you already have a Google Cloud account, that does not happen: AI Studio shows no projects until you import them through **Dashboard → Projects → Import projects**.
**2. Create the key.** Go to the **API Keys** page and click **Create API key** (older interface versions label the same action **Get API key**). Copy the string immediately and put it in a password manager.
**3. Handle the permission error, if you get one.** If the button is greyed out with *"You do not have permission to create a key in this project"*, you are missing IAM permissions on that project, not on your Google account — most importantly `apikeys.keys.create`. If no administrator can grant them, create a fresh project outside the organization and issue the key there.
**4. Smoke-test before you write any code.** One request tells you whether the key works:
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" \
-d '{"contents":[{"parts":[{"text":"ping"}]}]}'
JSON with text in it means you are through. An error means you skip ahead to the troubleshooting section instead of debugging your application code for an hour.
A note on availability: the Gemini API is not offered in every country. Google publishes a supported-regions list, and if your account or IP falls outside it, requests are refused on location grounds — developers there usually work through a hosted proxy provider instead.
Standard keys versus auth keys: the deadline you should not miss
This is the part that trips up anyone following an older tutorial.
Google is moving the Gemini API from **standard API keys** to **authorization (auth) keys**. Standard keys only associate a request with a project — they say nothing about who is calling. Auth keys are bound to a Cloud service account, so requests run under that identity, they are restricted to the Gemini API by default, and Google can shut them down fast when a leak is detected.
Three practical consequences:
- Every new key created in AI Studio today is already an auth key. You do not have to do anything special.
- Unrestricted standard keys are **already** rejected. If an old key stopped working without any change on your side, this is usually why.
- Standard keys stop working entirely in **September 2026**. Check the **Key Type** column on the AI Studio API Keys page. Anything marked *Standard* needs replacing before then.
Migrating is mechanical: create a new key, update your environment variables and deployment config, verify the application, then revoke the old one. Do it in that order — revoking first buys you an outage.
A related cleanup rule: since May 2026, unrestricted keys left dormant for a long stretch are blocked automatically and carry a **Blocked** tag in AI Studio. Unused keys are not free to keep around.
What the free tier actually gives you
The free tier needs no credit card, and on the models it covers, input and output tokens genuinely cost nothing — the current Flash models, for instance. Not every model is included, so check the pricing page for the one you plan to call.
The trade-off is not money, it is data and throughput.
**Data.** On the free tier, your prompts and responses may be used to improve Google's products. On the paid tier they are not. If you send anything client-confidential, that single line decides the tier for you, regardless of budget.
**Throughput.** Limits are measured on three axes: requests per minute (RPM), input tokens per minute (TPM) and requests per day (RPD). Exceeding any one of them returns an error even if the other two have headroom. Two details matter more than the raw numbers:
- Limits apply **per project**, not per key. A second key in the same project buys you nothing.
- The daily counter resets at midnight Pacific time, not at your local midnight.
I deliberately will not print a table of per-model RPM and RPD figures: Google revises them without announcement, and every static table on the web goes stale within a quarter. AI Studio shows your live limits on its rate-limit page — the only numbers worth trusting.
The shape of the free tier is predictable, though. It covers prototypes, manual experiments and a small bot, and it does not cover a content pipeline: one long article in my own workflow costs between eight and twenty model calls, so a daily allowance disappears after a handful of pieces. Linking a billing account moves you to Tier 1 and raises the ceilings; higher tiers unlock on cumulative spend, each with its own spend cap as a safety net.
Connecting the key to your code
One rule outranks every code sample below: **the key never goes into your source files.** Not in the repository, not in a screenshot, not pasted into a chat. It lives in an environment variable.
The official SDKs read `GEMINI_API_KEY` or `GOOGLE_API_KEY` automatically. If both are set, `GOOGLE_API_KEY` wins.
**Python:**
export GEMINI_API_KEY="AIza..."
import os
from google import genai
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Write three headline options about API rate limits",
)
print(response.text)
You can drop the `api_key` argument entirely — the client picks up the environment variable on its own. In production that is the safer form, because the value never appears in code at all.
**Node.js:**
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Give me three headline ideas",
});
console.log(response.text);
**Gemini CLI** uses the same environment variable and needs no config file: export the value, run the command, and you have a working prompt in the terminal. On a server it reads the variable from the process environment, so CI needs no extra wiring. If the CLI warns that the project is on the free tier, that is not an error — it is telling you which limits apply.
One habit that pays off later: keep the model name in a single place in your configuration. Google's model line moves fast, and a hardcoded model string scattered across a dozen files is a slow migration waiting to happen.
Reading the errors: invalid key, 400, 403, 429
Four responses account for nearly every support question I get.
**API key not valid.** The string was copied with a trailing space or line break, came from a different project, was revoked, or went into the wrong header. Confirm the key belongs to a project where the Gemini API is enabled, issue a fresh one, and re-run the curl test above.
**400 Bad Request.** Not an access problem at all. The request body is malformed: broken JSON, a missing required field, or a model name that does not exist. The response usually names the offending field — read the message, not just the code.
**403, User location is not supported for the API use.** Geography. A new key will not help, because the check is on the account region and the originating IP, not on the key.
**429, RESOURCE_EXHAUSTED.** You hit a limit. The official remedies, in order of effect: lower your request rate and concurrency, shorten prompts and responses, add retries with exponential backoff, and confirm you are reading the quota for the exact project and model you are calling. Enabling billing raises the ceiling but never removes limits. And because quotas are per project, check whether a second application is quietly eating the budget you thought was yours.
Keeping the key from leaking
Google's documentation gives key storage several sections in a row. The short version:
- Keep the value in environment variables; add `.env` to `.gitignore`. Never commit a key to version control.
- Never ship a key in client-side web or mobile code — it can be extracted from the bundle. Put a backend proxy in front of the API instead.
- Strip keys out of logs, stack traces and build artifacts. They leak from there far more often than from source code.
- Restrict the key to the Gemini API, and add IP or referrer restrictions where your setup allows it.
- Rotate on a schedule: create the replacement, switch the application over, verify, then revoke the old key.
- Set billing alerts in the Cloud Console so a spike arrives as a notification rather than an invoice.
If you suspect a leak, act before you investigate: issue a new key, deploy it, disable the compromised one, then audit the usage logs. A revoked key costs you ten seconds. Someone else's token bill does not — the real risk of a leaked key is rarely the stranger's prompts, it is the invoice attached to them.
When you do not need a key at all
Owning a key and writing the code around it makes sense when you are building a product. If your goal is a steady stream of SEO articles published into a CMS, the key becomes one more link in the chain that you have to issue, pay for, hide and rotate.
Both models exist side by side in our service: you can run on system keys and skip the registration entirely, letting the [SEO article generator](https://ai-seowriter.ru/en/generator-seo-statej) work through a keyword cluster, or plug in your own keys if you already have model access configured and paid for. The walkthrough on [automating SEO article publishing to WordPress](https://ai-seowriter.ru/en/blog/avtomatizatsiya-publikacii-seo-statey-wordpress) covers the publishing half of that pipeline.
The honest limit: you cannot write code against Gemini through an intermediary. For development you need your own access — this applies to the content task only.
FAQ
**How much does access cost?** The free tier requires no card and is capped by rate limits. Paid access runs through Google Cloud Billing and is charged per token, at prices that differ by model.
**Can I use one key across several applications?** Technically yes, practically no. They share quota and share the blast radius: one leak takes down every app using that key. Issue one key per application.
**Where do I see my existing keys?** On the API Keys page in AI Studio, with the key type and last-used date. AI Studio lists only keys that are unrestricted or restricted to the Gemini API; anything else lives in the Cloud Console credentials page.
**My key stopped working and I changed nothing.** Check three things in order: whether it was revoked, whether it was blocked as a dormant or unrestricted standard key, and whether regional checks now apply to your IP.
Automate SEO publishing with SEO Writer
AI writes articles, publishes to CMS, fills meta tags — without your involvement
Start for free →Read also
Invalid API Key OpenAI: Fix the 401 Error
Getting a 401 invalid_api_key from OpenAI? Here is the fast checklist, the real causes, a curl test, and how 401 differs from 403 and 429.
OpenRouter Free Models: Limits and Trade-offs
What OpenRouter free models really give you: current rate limits, what your prompts pay for, how to pick one, and when to move to paid.
How to Get an OpenAI API Key (ChatGPT API)
Create an OpenAI API key step by step: project vs user keys, billing tiers, curl and Python calls, safe storage, and spend limits.
SEO Writer integrations