Guides · AI Stack · 30

Get API keys for every major model and make your first call safely

Open developer accounts at Anthropic, OpenAI, Google, xAI and OpenRouter, cap what each can spend, store the keys safely, and make your first API call from the terminal, Python and JavaScript.

1-2 hoursFree to start + API usageIntermediate

A chat app is an AI model inside someone else's interface. The API is the same models, called from your own scripts, automations and agents, and billed by the token. This guide gets you a key from each major provider, a ceiling on what each can spend, and a first call that works, without leaking a key along the way.

1Know what the API gives you, and what your subscription doesn't cover

Use the API to run AI inside your own scripts, automations or product, to pick a cheaper model per task, and to get business data terms: Anthropic, OpenAI and xAI don't train on API traffic by default, and neither does Google on its paid tier. Instead of message caps, you pay per token, within rate limits.

Your chat subscription is a separate product. As of October 2026:

Chat planIncludes API calls?What to know
Claude ProNoBilled separately in the Claude Console. Max and Team include monthly API credits ($100 on Max 5x, $200 on Max 20x, $20 or $100 per Team seat, capped at $500), linked under Billing in claude.ai settings. Unused credit expires monthly
ChatGPT Plus or ProNoOpenAI bills API usage separately, on the OpenAI Platform
Google AI Pro or UltraPartly$10 (Pro) or $100 (Ultra) a month in Google Cloud credits for the Gemini API, once activated in the Google Developer Program
Grok (The X Subscription)PartlyPlus, Premium, Super and Ultra list "Grok API" and say the weekly usage pool covers API access (x.ai/pricing, checked October 13, 2026). Past the pool, or without a plan, the xAI Console runs on prepaid credits
OpenRoutern/aNo chat plan. One prepaid balance pays for hundreds of models

2Create an account and a key at each provider

Use a work email and two-factor sign-in. Create one key per app and name it after the job ("invoice-bot-dev"), so you can revoke one without breaking the rest.

ProviderWhere the key livesVariableFree start (October 2026)
Anthropic (Claude)Claude Console: Settings > API keys > Create key, with an expiration and workspace. Starts with sk-ant-, shown onceANTHROPIC_API_KEYA small free credit for new users
OpenAI (GPT)OpenAI Platform API keys page. Pick a project and permissions (All, Restricted, Read only)OPENAI_API_KEYNone verified. Prepaid, $5 minimum
Google (Gemini)Google AI Studio: Create API key. Each key belongs to a Cloud projectGEMINI_API_KEYFree tier on Flash and Flash-Lite, no billing
xAI (Grok)xAI Console API Keys page, after loading creditsXAI_API_KEYNone documented
OpenRouter (one key, many models)openrouter.ai/keys: name the key, set a credit limitOPENROUTER_API_KEY:free models: 50 requests a day, 1,000 after buying $10 of credits
  • Google's free tier costs you data. Under the Gemini API terms, free-tier prompts can improve Google's products and be read by human reviewers, so send nothing confidential. If a key shows Unrestricted, hover over it and choose Add restrictions > Restrict to Gemini API only.
  • OpenRouter passes through provider prices with no markup and charges 5.5% when you buy credits by card: one key and one bill for many models.
  • OpenAI's Restricted permission limits a key to the endpoints a script needs. Use it for anything unattended.

3Cap spending before your first call

Prepaid credit is your first ceiling: with auto-reload off, a key can only spend what's in the account. Then set a monthly cap in each console.

ProviderHard capAlerts and traps
AnthropicSettings > Billing > Spend limits > Set limit. Requests fail at the limitPer-workspace caps and alerts: Settings > Workspaces, pick one, Spend limits. Keep auto-reload (Settings > Billing) off or small
OpenAIOrganization limits: Spend > Edit spend limit, set a monthly limit, turn on Enforce a hard limit. Projects have their own Limits pageSpend alerts only notify. Auto-reload is on by default when you first buy credits: turn it off or cap it
GoogleAI Studio Spend page: Monthly spend cap > Edit spend cap (experimental)Billing data lags about 10 minutes, so you can overshoot. Cloud budgets alert at 50%, 90% and 100% but don't stop spending
xAIPrepaid credits, with the invoiced spending limit left at $0 (Billing > API Credits)Auto top-up (Billing > API spend management) takes a monthly maximum. Warns at 80%
OpenRouterA credit limit on every key (daily, weekly or monthly reset), plus workspace guardrail budgetsIts docs warn an unlimited key can spend your whole balance, auto top-ups included

4Store keys like passwords

  • Master copy in a password manager, noting where each key is used.
  • On your machine, a .env file listed in .gitignore before your first commit.
  • Never in code, chats (AI chats included), screenshots, shared docs, or a website or app front end.
  • One key per person and app. Anthropic and OpenAI both say don't share keys. Anthropic suggests rotating every 90 days.
.env (keep it out of git, never share it)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=...
GEMINI_API_KEY=...
XAI_API_KEY=...
OPENROUTER_API_KEY=...
Ignore the file, then check that git really ignores it
echo ".env" >> .gitignore
git check-ignore -v .env     # prints the matching rule if .env is ignored

Python reads it with python-dotenv (load_dotenv()). Node.js 20.6+ reads it with node --env-file=.env app.js.

5Make your first call from the terminal

Load .env into your shell, then run a call. Small models and a short prompt keep each one under a cent.

Claude (Anthropic) with curl
set -a; source .env; set +a      # loads the keys into this terminal only
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-haiku-5-5",
    "max_tokens": 1000,
    "messages": [{"role": "user", "content": "Say hello in five words."}]
  }'
GPT (OpenAI) with curl
curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model": "gpt-6-luna", "input": "Say hello in five words."}'
Gemini (Google, free tier) with curl
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.8-flash", "input": "Say hello in five words."}'

The usage numbers in the reply are what you paid for. A 401 means the key is wrong or not loaded. A 429 means a rate limit or spend cap (on Claude, your own spend limit returns a 400 that says so). If a model name is rejected, check the provider's models page: names change often.

6Call from Python and JavaScript, including OpenAI-compatible APIs

Python: Claude (pip install anthropic python-dotenv)
from dotenv import load_dotenv
import anthropic

load_dotenv()                    # reads ANTHROPIC_API_KEY from .env
client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Give me three names for a bakery."}],
)
for block in message.content:
    if block.type == "text":
        print(block.text)
print(message.usage)             # the tokens you paid for

Many providers accept OpenAI's SDK with a different base URL and key (model IDs as of October 2026):

ProviderBase URLKeyExample model
OpenAIDefault, leave it outOPENAI_API_KEYgpt-6-luna
OpenRouterhttps://openrouter.ai/api/v1OPENROUTER_API_KEYanthropic/claude-sonnet-5.5
Google Geminihttps://generativelanguage.googleapis.com/v1beta/openai/GEMINI_API_KEYgemini-3.8-flash
xAIhttps://api.x.ai/v1XAI_API_KEYgrok-4.7 (xAI's docs prefer client.responses.create)
Python: any OpenAI-compatible provider (pip install openai python-dotenv)
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)
reply = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Give me three names for a bakery."}],
)
print(reply.choices[0].message.content)
print(reply.usage)
JavaScript: any OpenAI-compatible provider (npm install openai)
// save as hello.mjs, run with: node --env-file=.env hello.mjs
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
});

const reply = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "Give me three names for a bakery." }],
});
console.log(reply.choices[0].message.content);
console.log(reply.usage);

For Claude in JavaScript, use @anthropic-ai/sdk and the TypeScript tab of Anthropic's quickstart.

7Work out what it will cost

  • You pay per million tokens (MTok), with separate input and output rates. Output costs more: 5x on Claude Sonnet 5.5.
  • Tokens are word pieces. On Claude's current tokenizer, 1M tokens is roughly 555,000 words. Providers count differently, so trust the usage field.
  • Input is everything you send each call, including the whole conversation so far. Long chats cost more per turn.
  • Tools cost extra. Claude's web search is $10 per 1,000 searches plus tokens.

The formula: (input tokens × input price + output tokens × output price) ÷ 1,000,000.

Worked example (Anthropic prices as of October 2026): a script drafts replies to 1,000 customer emails a month. Each call sends 3,000 tokens (instructions plus the email) and gets 500 back.

ModelPrice per MTok (in / out)Per email1,000 emails
Claude Haiku 5.5$0.10 / $0.50$0.0003 + $0.00025 = $0.00055$0.55
Claude Sonnet 5.5$2 / $10$0.006 + $0.005 = $0.011$11
Claude Sonnet 5.5 via the Batch API (50% off, not instant)$1 / $5$0.0055$5.50
Claude Fable 5.1$10 / $50$0.03 + $0.025 = $0.055$55

Same job, a 100x spread. Start with the cheapest model that does it well, and check prices when you build: Google has scheduled increases for several Gemini models on December 1, 2026 and January 1, 2027. Current prices: Claude, OpenAI, Gemini, xAI, OpenRouter.

Estimate my monthly API cost (works in any chatbot)
I'm planning to use an AI API for: [the job, e.g. "summarize 200 sales calls a month"].
Each run sends about [X] words of instructions and input, and gets about [Y] words back.
It will run about [N] times a month.
Current prices per million tokens, copied from the provider's pricing page: [paste rows].
Estimate tokens per run (show your conversion), cost per run and cost per month for the
two cheapest models that could do this well and one premium model. Then suggest a monthly
spend cap, and list anything that would push the real cost higher (long chat history,
retries, web search, images, agent loops).
API setup checklist0/7

What's next

Before you connect a key to email, files or the web, read Use AI safely and cheaply. Then build an agent with the Agent SDK, run it on a small server, or connect it to your tools with MCP.

Get the next lesson in your inbox

Your free AI path in the right order, plus new guides when they come out.

Free. No card. One click to unsubscribe.

Want it done,not just learned?

The AI Skill Pack: 13 ready Claude Skills for your inbox, weekly report, meetings, content, research, proposals and SOPs. Installed in ten minutes. $27, one time.

See the AI Skill PackOr keep going free: everything in one place