Skip to content
trending

Guides

API Key Guide: OpenAI, Claude, Gemini & OpenRouter

How to get an API key from OpenAI, Anthropic, Google AI Studio and OpenRouter, store it securely in .env, set spending limits, and respond to a leak.

By 10 min read
API Key Guide: OpenAI, Claude, Gemini & OpenRouter

Update (9 Nov 2026): Claude Fable 5.2 and Mythos 5.2 are out - prices, access and benchmarks are in my Claude Fable 5.2 guide.

👁 117 reads

An API key is a long string of characters that identifies you and your account with every request to an AI model. It works like a password combined with a payment card: whoever has it can spend your money. Below we show you how to get a key from OpenAI, Anthropic, Google AI Studio and OpenRouter, how to store it securely, and what to do if it leaks. This is the second step in the AI API from scratch path.

Status as of October 4, 2026

  • Without a card: Google AI Studio key (free tier Gemini API) and OpenRouter (free models only, 50 requests daily).
  • With a card: OpenAI and Anthropic work on prepaid credit, OpenRouter on top-ups with a 5.5% fee (min. $0.80).
  • Hard spending limits: OpenAI since July 22, 2026 (per organization and project), Anthropic (per organization and workspace), OpenRouter (per key, with daily, weekly or monthly reset).

Which API Key to Choose When Starting Out

If you’re just learning, start with one of these two:

  • OpenRouter - one key for over 460 models from all providers, shared balance, code compatible with OpenAI SDK. We tested all scripts in this path with it. Details in the guide OpenRouter: one key for all models.
  • Google AI Studio - free tier Gemini API without a card. Good for first experiments, but with low and non-guaranteed limits.

A key directly from OpenAI or Anthropic makes sense when you already know which model you’re using, need higher limits, or require a contract with a specific provider (e.g. for processing company data).

OpenAI: Step-by-Step API Key Setup

  1. Go to platform.openai.com and create an account (this is a different account from ChatGPT subscription, though you log in with the same email).
  2. In Settings → Billing add a card and load credit. OpenAI API works on prepaid credit: when credits run out, requests get a credit_balance_exhausted error.
  3. Create a project (Settings → Projects) - keys always belong to a project.
  4. In API keys click Create new secret key, give it a name and copy the key immediately. It starts with sk-proj- and you won’t see it in full later.
  5. Set a limit: Settings → Project settings → Limits → Spend → Edit spend limit and check hard enforcement. “Alert” alone only sends an email, it doesn’t stop spending.

After exceeding the hard limit, requests get a 429 error with code project_spend_limit_exceeded. OpenAI notes that the limit doesn’t work instantly, so spending may slightly exceed it. We broke down model pricing in the article How much GPT-6 Sol and Luna cost.

Anthropic (Claude): Step-by-Step API Key Setup

  1. Go to platform.claude.com (formerly console.anthropic.com) and create an organization account. Claude Pro subscription doesn’t give API credits.
  2. In Settings → Billing purchase credits. According to documentation, new accounts get a “small” pool of free credits for testing; Anthropic doesn’t specify exactly how much.
  3. In Settings → API keys create a key (starts with sk-ant-). Keys belong to a workspace, so it’s worth having a separate workspace for each project.
  4. In Billing → Spend limits set your own monthly limit. After reaching it, the API returns 400 with the message “You have reached your specified API usage limits”.

Regardless of your limit, each account tier has a ceiling: Start $500, Build $1,000, Scale $200,000 monthly. We described pitfalls when switching to the newest model in the article Claude Opus 5.5 in API: four changes that will break your code.

Google AI Studio (Gemini): API Key Without a Card

  1. Go to aistudio.google.com/apikey and log in with a Google account (you must be 18 years old; Poland is on the list of supported countries).
  2. Click Create API key. The key is created in a Google Cloud project, and limits count per project, not per key - a second key in the same project won’t give you a second pool.
  3. Without payment you work in the free tier: Flash models are free, but Google doesn’t publish fixed limits (you’ll see them in AI Studio). Pro and image models are paid only.
  4. When you attach a billing account, you enter Tier 1 and pay per token.

We described details of free limits and privacy in the guide Google AI Studio: API key, free limits and pricing.

OpenRouter: One Key for All Models

  1. Log in at openrouter.ai (Google, GitHub or email).
  2. In Settings → Keys click Create Key. Keys start with sk-or-v1-.
  3. Immediately set a Credit limit, e.g. $2, and reset monthly. Without a limit the key can spend your entire balance.
  4. Without a top-up, only models with the :free suffix work (50 requests daily). After purchasing at least $10 in credits, the free model limit increases to 1,000 daily.

Where to Store Your Key: Environment Variables and .env

Rule number one: the key never goes in the code. Don’t paste it in api_key="sk-...", because you send code to repositories, show it to colleagues or paste it in chat asking for help. The program should read the key from an environment variable. There are two ways.

In your project directory you create a .env file with the key, and the python-dotenv library will load it at startup. Template from our package (this is .env.example, a file without real keys that you can safely share):

# Copy this file as .env and enter your key. NEVER put the .env file in a repository.
OPENROUTER_API_KEY=sk-or-v1-paste-your-key-here
# Default model (any identifier from https://openrouter.ai/models)
MODEL=openai/gpt-6-luna

# Provider keys - only needed for scripts in the provider/ directory
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
GEMINI_API_KEY=

Next to it must be a .gitignore file that tells git to never send .env:

.env
.venv/
node_modules/
__pycache__/

System Environment Variable

On Windows you can set a variable permanently for your user. In PowerShell:

setx OPENROUTER_API_KEY "sk-or-v1-your-key"
# close and reopen terminal, then check (shows only length, not the key):
$env:OPENROUTER_API_KEY.Length

On Linux and Mac you add export OPENROUTER_API_KEY="..." to ~/.bashrc or ~/.zshrc. The OpenAI, Anthropic and Google SDKs automatically look for their variables: OPENAI_API_KEY, ANTHROPIC_API_KEY and GEMINI_API_KEY. Thanks to this, in code you just need OpenAI() without any argument.

Same Code with Provider Keys

Below are three minimal scripts that connect directly to OpenAI, Anthropic and Google. Honestly: we did not run them with real keys from these companies, because we did testing through OpenRouter. However, we did run them with deliberately fake keys to verify that the libraries install, the code executes, and each company’s servers respond. Libraries: openai 3.24.0, anthropic 1.11.0, google-genai 2.28.0.

"""Direct to OpenAI (key from platform.openai.com), Responses API.
pip install openai python-dotenv     Variable in .env: OPENAI_API_KEY=sk-proj-..."""
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()  # automatically reads OPENAI_API_KEY from environment variables

response = client.responses.create(
    model="gpt-6-luna",
    instructions="Answer in Polish, briefly.",
    input="Explain in two sentences what an API is.",
)
print(response.output_text)
print(response.usage.input_tokens, "+", response.usage.output_tokens, "tokens")
"""Direct to Anthropic (key from platform.claude.com), Messages API.
pip install anthropic python-dotenv     Variable in .env: ANTHROPIC_API_KEY=sk-ant-..."""
from dotenv import load_dotenv
import anthropic

load_dotenv()
client = anthropic.Anthropic()  # automatically reads ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,                     # in Anthropic max_tokens is required
    system="Answer in Polish, briefly.",
    messages=[{"role": "user", "content": "Explain in two sentences what an API is."}],
)
print(next(b.text for b in response.content if b.type == "text"))
print(response.usage.input_tokens, "+", response.usage.output_tokens, "tokens")
"""Direct to Google Gemini (key from aistudio.google.com), google-genai SDK.
pip install google-genai python-dotenv     Variable in .env: GEMINI_API_KEY=..."""
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()  # automatically reads GEMINI_API_KEY

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Explain in two sentences what an API is.",
    config=types.GenerateContentConfig(system_instruction="Answer in Polish, briefly."),
)
print(response.text)
print(response.usage_metadata.prompt_token_count, "+", response.usage_metadata.candidates_token_count, "tokens")

Here’s how the servers responded to a fake key (October 4, 2026):

# OpenAI
openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-**********************LUCZ. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}

# Anthropic
anthropic.AuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'API key is invalid.'}, 'request_id': None}

# Google
google.genai.errors.ClientError: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'API_KEY_INVALID', 'domain': 'googleapis.com', 'metadata': {'service': 'generativelanguage.googleapis.com'}}, {'@type': 'type.googleapis.com/google.rpc.LocalizedMessage', 'locale': 'en-US', 'message': 'API key not valid. Please pass a valid API key.'}]}}

Two things worth remembering. First, OpenAI masks the key in the message and only shows its end - never send anyone a full error message from another tool unless you’re certain it does the same. Second, Google responds to a bad key with code 400, not 401, so error handling based only on status number will miss this case.

How Not to Burn Your Key: 7 Rules

  1. One key per project. When something leaks, you disable one key, not everything.
  2. Limit on every key. In OpenRouter on the key, in OpenAI on the project, in Anthropic on the workspace. For learning, $2-5 monthly is enough.
  3. No keys in the browser. JavaScript code on a page is visible to every visitor. Keep the key on the server, and have the page query your server.
  4. .env in .gitignore before the first commit. Deleting the file in a later commit doesn’t help - the key stays in history.
  5. Don’t paste keys in AI chats, screenshots or recordings. When showing code, show .env.example.
  6. Disable automatic top-up on accounts where you’re just learning.
  7. Check usage once a week in the provider’s panel. A sudden spike is the first sign of a leak.

Key Leaked: What to Do in 10 Minutes

  1. Delete or disable the key in the provider’s panel. Immediately, before you start cleaning the repository. This is the only step that actually stops the damage.
  2. Create a new key and enter it in .env on your computer and server.
  3. Check usage from recent days. If you see someone else’s requests, write to the provider’s support - with quick reporting there’s sometimes a refund, but no one guarantees it.
  4. Clean repository history (e.g. git filter-repo --replace-text) and force push. Remember that copies and forks may have already been made, which is why step 1 is more important.
  5. Add protection for the future: limit on the new key and secret scanner (GitHub does this for free for public repositories).

GitHub automatically scans public repositories and reports found keys to companies in the partner program, including OpenAI, Anthropic, Google and OpenRouter. According to available descriptions, OpenAI disables the found key itself and sends an email. OpenRouter in documentation only promises email notification and asks for manual key deletion. So don’t count on automation - a limit on the key is your only guarantee.

Frequently Asked Questions

Is an API key free?

The key itself yes. You pay for tokens used. Without a card, Google AI Studio key (free tier Gemini) and OpenRouter key with free models work.

Does ChatGPT Plus or Claude Pro subscription give API access?

No. Chat subscriptions and API are separate accounts and separate billing. For API you pay from prepaid balance.

Where to find Claude API key?

On platform.claude.com in Settings → API keys. Keys start with sk-ant-. It shows in full only once, when created.

Can I use one key in multiple programs?

Technically yes, but better not. Separate keys let you see which program spends how much, and disable one without breaking the rest.

My key returns 401, though it’s correct. Why?

Most often: environment variable didn’t load (terminal opened before setx), there’s a space or quote in the wrong place in .env, the key belongs to a different provider than the address you’re sending to, or the key was disabled after leak detection.

Google · Your sourcesQuantslant higher in your Google - one clickAdd to preferred sources →

Sources and Verification Date

Verified October 4, 2026. We ran the code on Windows 11 with Python 3.13.15.

Kinetyra

// read next

More on this from QUANTSLANT

Piotr Olszewski

Editor and publisher · Quantslant

I edit and publish Quantslant. AI tools help with research, drafts and translation; choosing topics, running the tests, checking facts and the decision to publish are mine, and so is the responsibility for what appears here.

read nextYour First AI API Call in Python: Step-by-Step GuideguidesYour First AI API Call in Python: Step-by-Step GuideTen lines of code to query an AI model in Python: install the openai library, set your key, send messages, read the response.

Most read

  1. 1Best AI Video Generator Apps for Your Phone (2026)
  2. 2Claude Opus 5.5 Motion Graphics: 60s Showreel from One Prompt
  3. 3Wan 2.2 on RTX 4090: timings, VRAM and four test clips
// site map

This page in other languages1

Quantslant in numbers 1,427posts in archive26news from the last 7 days18video models in the observatory
🎬 AI Video Benchmarks: Higgsfield DoP vs OpenAI Sora • Higgsfield vs Runway Gen-3 • AI Video Credit Calculator
× ‹ enlarge ›