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 plan | Includes API calls? | What to know |
|---|---|---|
| Claude Pro | No | Billed 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 Pro | No | OpenAI bills API usage separately, on the OpenAI Platform |
| Google AI Pro or Ultra | Partly | $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) | Partly | Plus, 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 |
| OpenRouter | n/a | No 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.
| Provider | Where the key lives | Variable | Free start (October 2026) |
|---|---|---|---|
| Anthropic (Claude) | Claude Console: Settings > API keys > Create key, with an expiration and workspace. Starts with sk-ant-, shown once | ANTHROPIC_API_KEY | A small free credit for new users |
| OpenAI (GPT) | OpenAI Platform API keys page. Pick a project and permissions (All, Restricted, Read only) | OPENAI_API_KEY | None verified. Prepaid, $5 minimum |
| Google (Gemini) | Google AI Studio: Create API key. Each key belongs to a Cloud project | GEMINI_API_KEY | Free tier on Flash and Flash-Lite, no billing |
| xAI (Grok) | xAI Console API Keys page, after loading credits | XAI_API_KEY | None documented |
| OpenRouter (one key, many models) | openrouter.ai/keys: name the key, set a credit limit | OPENROUTER_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.
| Provider | Hard cap | Alerts and traps |
|---|---|---|
| Anthropic | Settings > Billing > Spend limits > Set limit. Requests fail at the limit | Per-workspace caps and alerts: Settings > Workspaces, pick one, Spend limits. Keep auto-reload (Settings > Billing) off or small |
| OpenAI | Organization limits: Spend > Edit spend limit, set a monthly limit, turn on Enforce a hard limit. Projects have their own Limits page | Spend alerts only notify. Auto-reload is on by default when you first buy credits: turn it off or cap it |
| AI 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 | |
| xAI | Prepaid 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% |
| OpenRouter | A credit limit on every key (daily, weekly or monthly reset), plus workspace guardrail budgets | Its 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
.envfile listed in.gitignorebefore 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.
ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=... GEMINI_API_KEY=... XAI_API_KEY=... OPENROUTER_API_KEY=...
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.
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."}]
}'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."}'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
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 forMany providers accept OpenAI's SDK with a different base URL and key (model IDs as of October 2026):
| Provider | Base URL | Key | Example model |
|---|---|---|---|
| OpenAI | Default, leave it out | OPENAI_API_KEY | gpt-6-luna |
| OpenRouter | https://openrouter.ai/api/v1 | OPENROUTER_API_KEY | anthropic/claude-sonnet-5.5 |
| Google Gemini | https://generativelanguage.googleapis.com/v1beta/openai/ | GEMINI_API_KEY | gemini-3.8-flash |
| xAI | https://api.x.ai/v1 | XAI_API_KEY | grok-4.7 (xAI's docs prefer client.responses.create) |
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)// 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
usagefield. - 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.
| Model | Price per MTok (in / out) | Per email | 1,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.
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).
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.