NewConnect Claude, Gemini, ChatGPT, and other AI agents to API Ninjas via our MCP server →

What Is an API Key? Examples and How to Keep It Safe

APIs & integration17 min read
A key icon next to a terminal sending a request with an X-Api-Key header and getting 200 OK

An API key is a unique code that identifies the app or developer making a request to an API. You send it with every request, usually in an HTTP header, and the API uses it to decide whether to answer, how many requests you get and whose account to bill.

If you have ever signed up for a weather, maps or AI service and copied a long string from a dashboard, that string was an API key. We've issued over 250,000 of them at API Ninjas. This guide covers what an API key is, how it works with real code examples, how it differs from OAuth tokens and JWTs, and how to keep yours from leaking.

What is an API key?

An API key is a long, random string that an API provider gives you when you sign up. It works like a membership card: it tells the service which account a request belongs to, but it does not prove who is holding it.

That last point matters. Most API keys are bearer credentials, which means anyone who has the key can use it as if they were you. There is no second factor and no password prompt, so a leaked key can run up your bill or use up your quota until you replace it.

What does an API key look like?

Keys are long strings of letters and numbers, from about 20 characters to well over 100. Many providers add a short prefix so you, and automated leak scanners, can tell what kind of key it is at a glance. The examples below are shortened on purpose: a full-length key pasted into a blog post or a public repository can set off those scanners.

Key starts withWhose keyExample (shortened)What the format tells you
sk-proj-OpenAIsk-proj-Qw3r…t9ZaA secret key tied to one OpenAI project.
sk-ant-Anthropic (Claude)sk-ant-api03-Hd8…Kq2A secret key for the Claude API.
AIzaGoogle Cloud and GeminiAIzaSyD9…kFMBA Google API key. Since 2026 it may unlock paid AI calls, so restrict it (see below).
sk_live_ / pk_live_Stripesk_live_51Hc…q7Dcsk_ = secret, server only. pk_ = publishable, safe in a web page. live = real money.
ghp_ / github_pat_GitHubghp_7Lx2…Rw4PA personal access token, which works like a key to your GitHub account.
No prefixMany smaller APIsXb3k9Qm…EuGA plain random string. Treat it as secret.

The exact format does not matter to you as a developer. What matters is which kind of key you hold: a secret key that must stay on your server, or a publishable key that is designed to be seen.

How does an API key work?

Your app attaches the key to each request, and the API checks it before doing any work. The whole exchange takes a few milliseconds:

  1. Your code sends a request with the key attached, usually in a header such as X-Api-Key or Authorization.
  2. The API looks the key up and finds the account, plan and permissions tied to it.
  3. It checks the rules for that account: is the key active, is this endpoint included in the plan, is there quota left?
  4. If every check passes, the API does the work and returns the data. It also counts the request against your quota.
  5. If a check fails, you get an error instead. A missing or unknown key usually returns 401 Unauthorized, a key without access to that endpoint 403 Forbidden, and a key over its limit 429 Too Many Requests. Some APIs use 400 Bad Request with an error message, so read the response body.
How an API checks a key: four checks, each with its own errorRequest arrivesKey sent?Missing key: usually 401Check the header name and env variablenoyesKey recognized?Unknown key: usually 401Look for spaces, quotes or an old keynoyesEndpoint in plan?Not in your plan: 403Upgrade, or call an endpoint you havenoyesQuota left?Over the limit: 429Wait, retry with backoff, or upgradenoyes200 OK: data returnedThe call counts against your quota
How an API checks a key: four checks, each with its own errorRequest arrivesKey sent?noMissing key: usually 401Check header name, env varyesKey recognized?noUnknown key: usually 401Look for spaces or an old keyyesEndpoint in plan?noNot in your plan: 403Upgrade your planyesQuota left?noOver the limit: 429Wait, retry later, or upgradeyes200 OK: data returnedCounts against your quota
Every request passes four key checks before the API does any work. The order varies between APIs, but a request only gets data once it passes all four.

Header or query string?

There are two common places to put a key. Most modern APIs prefer the header, and many accept both.

WhereExampleTrade-off
HTTP header (recommended)X-Api-Key: YOUR_API_KEYNot stored in browser history or most server logs.
Query string?api_key=YOUR_API_KEYEasy to test in a browser, but the key ends up in logs, analytics and shared links.

A key in the query string also leaks through the Referer header when a page links elsewhere, and through any screenshot of the address bar. Use the query string only for quick tests.

You will also see Authorization: Bearer YOUR_KEY instead of X-Api-Key. Both are headers and both are fine; the API's documentation tells you which one it expects.

Example: calling an API with a key

These examples call the API Ninjas Exchange Rate API. The same pattern works for almost any API that uses keys.

cURL
curl -H "X-Api-Key: YOUR_API_KEY" \ "https://api.api-ninjas.com/v1/exchangerate?pair=USD_EUR"
rate.py
import os import requests api_key = os.environ["API_NINJAS_KEY"] # read the key from the environment, not the code response = requests.get( "https://api.api-ninjas.com/v1/exchangerate", params={"pair": "USD_EUR"}, headers={"X-Api-Key": api_key}, timeout=10, ) response.raise_for_status() print(response.json())
rate.mjs (Node.js 18+, on a server)
const response = await fetch( "https://api.api-ninjas.com/v1/exchangerate?pair=USD_EUR", { headers: { "X-Api-Key": process.env.API_NINJAS_KEY } } ); if (!response.ok) throw new Error(`Request failed: ${response.status}`); console.log(await response.json());

To send the same request from Postman:

  1. Open your request and go to the Authorization tab.
  2. Set Auth Type to API Key.
  3. Enter X-Api-Key as the Key and {{api_ninjas_key}} as the Value.
  4. Set Add to to Header, then store the real key in a Postman environment variable called api_ninjas_key, so it isn't saved in the shared collection.

Notice that none of the examples type the key into the code. They read it from an environment variable, which is the first habit that keeps a key from leaking (more on that below).

If the key is missing or wrong, the API refuses before doing any work. For example, API Ninjas answers with HTTP 400 and a short message (see the full list of error codes):

Response (HTTP 400)
{"error": "Invalid API Key."}

What are API keys used for?

An API key answers one question for the provider: which account is this request from? Almost everything else an API does with keys follows from that.

  • Identifying the project. The key ties each request to an account or app, not to a person. Two apps on the same account can have separate keys.
  • Quotas and rate limits. The API counts requests per key, for example 100 requests an hour or 100,000 a month, and refuses requests over the limit.
  • Billing. Paid APIs charge per key or per account, so the key decides whose invoice a request lands on.
  • Plan features. A key on a paid plan can unlock endpoints, fields or fresher data that a free key cannot.
  • Usage analytics. Dashboards that show your calls per day, errors and top endpoints are built from requests grouped by key.
  • Cutting off access. If a key leaks or an app is retired, the provider can disable that one key without touching anything else.

What a key is not good at is identifying the person using your app. If you need to know which user is signed in, or let users grant your app access to their own data, you need a user-level method such as OAuth. The OWASP API Security Top 10 is blunt about it: “API keys should not be used for user authentication.” The next section compares them.

API key vs. token: what's the difference?

An API key identifies an app or account and usually lasts until you replace it. A token, such as an OAuth access token, identifies a user who signed in and expires within minutes or hours. People often mix them up because both are strings you send in a header.

MethodWhat it identifiesWho creates itHow long it lastsTypical use
API keyYour app or accountYou, in the provider's dashboardUntil you rotate or delete itServer-to-server calls to data APIs
OAuth 2.0 access tokenA user, plus what they allowed your app to doAn authorization server, after the user signs inMinutes to hours, refreshed as needed“Sign in with Google”, reading a user's calendar or files
JWT (JSON Web Token)Whatever is written inside it: often a user and their permissionsYour auth server or identity providerSet by its expiry claim, usually shortSessions and access tokens. A JWT is a token format, so an OAuth token can be a JWT.
Username and password (Basic auth)A personThe personUntil they change itOlder APIs and internal tools. Avoid it for new work.

API key vs. bearer token

“Bearer” describes how a credential is sent, not what it is. Authorization: Bearer <value> means “whoever bears this value gets access,” and the value can be an OAuth access token, a JWT or a plain API key. So the real question is which credential an API expects, and its documentation will say.

API key vs. client ID and secret

Some providers give you two values instead of one. The client ID is like a username and can be visible. The client secret is like a password, and your server uses the pair to get short-lived tokens through OAuth. A single API key skips that exchange, which is simpler but means the key itself must never leak.

API keys and MCP

MCP (Model Context Protocol) is the standard way AI agents connect to outside tools. It is not a replacement for API keys: an MCP server is a tool server, and it usually still needs a key in a header, or an OAuth sign-in, to reach the API behind it. Our post on connecting AI agents to live data with MCP shows both.

Secret keys vs. publishable keys

Some providers give you a pair of keys. The secret key can do everything, including charging cards or deleting data, so it lives only on your server. The publishable key is built to sit in a web page or mobile app, and it can only do narrow things such as starting a checkout.

If a provider gives you only one key and doesn't say it is publishable, treat it as secret.

When a “public” key stops being harmless

For years, Google's Firebase documentation said its browser-side API keys were not secrets. Then the same AIza keys started working with Google's Gemini AI models, which bill per request. In February 2026, Truffle Security reported 2,863 live Google keys sitting in public web pages that could call Gemini.

Google has since tightened the rules. Its documentation now says the Gemini API “rejects requests from unrestricted standard keys,” and keys created in Google AI Studio since May 28, 2026 are a stricter “auth key” type.

The lesson applies to every provider: a key is as risky as everything it can reach, not just what you meant it for. Restrict each key to the APIs it needs.

When an API key is enough

A key is the right choice when your own server calls an API on behalf of your app, such as fetching exchange rates, weather or stock prices. Reach for OAuth when you act on behalf of individual users and their own data.

How to get an API key

The steps are nearly the same everywhere:

  1. Create an account with the API provider and confirm your email.
  2. Open the dashboard page called something like API keys, Credentials or Developer settings.
  3. Create a key. Give it a name that says where it will be used, such as billing-service-prod.
  4. Add restrictions if the provider offers them: allowed IP addresses, allowed websites, or only the endpoints you need.
  5. Copy the key straight into a password manager or your secrets store. Some providers show it only once.

Example: getting an API Ninjas key

  1. Create a free account. No credit card is required.
  2. Sign in and open your profile page.
  3. On the API Statistics tab, click Show API Key, then copy it.
  4. Send it in the X-Api-Key header, as in the examples above.

To replace the key later, click Change API Key on the same tab and confirm. The old key stops working right away, so update your apps first.

Why is my API key not working?

Key problems are common. In one week of November 2026, across 33 of our most-used APIs, about 1 in 20 requests was turned away because of the key: 2.9% arrived with no key at all, and 2.1% with a key we didn't recognize. Much of that is automated traffic, but a missing key is the more common failure, and in your own app it usually points to a header name or an environment variable that didn't load.

Match the error you see to the likely cause:

What you seeLikely causeFix
“Missing API key” (often 401)Header name misspelled, or the environment variable is emptyPrint the header name and check the variable is set before the request runs
“Invalid API key” (often 401)A space, quote marks or a line break copied with the keyRemove quotes around the value in .env and trim the key: os.environ["API_NINJAS_KEY"].strip()
“Invalid API key” right after you changed itYour app still sends the old keyUpdate the key everywhere and restart or redeploy
“Invalid API key” with X-Api-KeyYou added Bearer in front of the keySend only the key in X-Api-Key; Bearer belongs in the Authorization header
403 ForbiddenThe endpoint or field isn't in your plan, or the key is restricted to other IPs or sitesCheck your plan and the key's restrictions
429 Too Many RequestsYou hit the rate limit or the monthly quotaSlow down, retry with backoff, or upgrade
Works with curl, fails in the browserThe browser blocks the call, or the key isn't in your front-end build (by design)Call the API from your server instead
Works locally, fails in productionThe environment variable isn't set on your hostAdd it in your hosting dashboard and redeploy

For API Ninjas, both key errors return HTTP 400 with a message, and the error codes page lists the rest.

How to keep your API key safe

Treat a secret API key like a password that can spend money. Leaks are common: GitGuardian counted 28,649,024 new secrets in public GitHub commits in 2025, and GitHub says a new one appears in public code about once every two seconds. These eight habits prevent almost every leak.

1. Keep keys out of your code

Put the key in an environment variable or a .env file, and keep that file out of version control.

.env (never commit this file)
API_NINJAS_KEY=paste_your_key_here
.gitignore
.env
config.py
# pip install python-dotenv import os from dotenv import load_dotenv load_dotenv() # reads .env into the environment api_key = os.environ["API_NINJAS_KEY"]

Once a key has been committed, deleting the file is not enough. It stays in your Git history, so replace the key.

2. Never put a secret key in browser or mobile code

Anything you ship to a user's device can be read. A key in JavaScript shows up in the browser's developer tools, and a key in a mobile app can be pulled out of the app file in minutes.

Watch out for framework prefixes. Variables named NEXT_PUBLIC_* in Next.js or VITE_* in Vite are copied into the code sent to the browser, so a secret key must never use them.

Instead, have the browser call your own server, and let the server add the key. Here is a minimal Next.js route that does it:

The browser calls your server, and only your server sends the API keyGET /api/rate+ X-Api-Key headerBrowser or mobile appCalls your server onlyHolds no API keyYour serverKey in an env variableAdds the X-Api-Key headerChecks login and rate limitThe APIChecks the key and quotaReturns the dataAnyone can read code hereThe key never leaves hereSees only your server
The browser calls your server, and only your server sends the API keyBrowser or mobile appCalls your server only. Holds no API key.GET /api/rate+ X-Api-Key headerYour serverKey in an env variableAdds the X-Api-Key headerChecks login and rate limitThe key never leaves hereThe APIChecks the key and quota, returns the data
Solid arrows are the request, dashed arrows the response. The browser never holds the key, so there is nothing in the page to copy.
app/api/rate/route.js
// Runs on the server, so the key never reaches the browser export async function GET(request) { const pair = new URL(request.url).searchParams.get("pair") ?? "USD_EUR"; const response = await fetch( `https://api.api-ninjas.com/v1/exchangerate?pair=${encodeURIComponent(pair)}`, { headers: { "X-Api-Key": process.env.API_NINJAS_KEY } } ); return Response.json(await response.json(), { status: response.status }); }

Your front end then calls fetch("/api/rate?pair=USD_EUR") and never sees the key. Add your own login check or rate limit to that route, or anyone can use it to spend your quota.

3. Check what AI coding tools write

AI assistants and app builders often paste a key straight into front-end code to get a demo working. Before you deploy, search the generated code for your key and ask the tool to move the call to a server route.

4. Use one key per app and environment

Separate keys for development, staging and production, and for each app, mean a leak in one place can be fixed without breaking the others. If the provider supports restrictions, limit each key to the IP addresses, websites or endpoints it needs.

5. Rotate keys on a schedule

Replace keys every few months, and always when someone with access leaves the team. If the provider allows two active keys, switch your apps to the new one before you delete the old one.

6. Turn on secret scanning

GitHub's secret scanning and push protection block a commit that contains a known key format. Push protection is on by default for your personal pushes to public repositories; turn on secret scanning for your private and organization repositories too. GitHub says push protection stops about 30% of new secrets before they enter a repository's history, so treat it as a safety net, not a plan.

7. Don't log keys, and watch your usage

Redact keys from logs, error messages and support tickets. Check your usage dashboard now and then: a sudden spike in calls is often the first sign that a key has leaked.

8. Set spending caps and billing alerts

If a provider lets you set a monthly spending limit, set one. If it doesn't, set a billing alert. The OWASP API Security Top 10 recommends exactly this, with an example scenario where abuse pushed a monthly bill from about $13 to $8,000.

API keys and AI tools

Many people meet API keys for the first time when an AI app asks for one. The same rules apply, with a few twists.

Pasting your key into an AI app

Some chat apps, coding tools and character apps ask for your OpenAI, Anthropic or Google key. This is called “bring your own key”: the app sends requests to the AI provider under your key, so every message is billed to your account.

  • Create a separate key just for that app, so you can revoke it without breaking anything else.
  • Set a monthly spending limit in the AI provider's dashboard before you paste the key.
  • Only use apps you trust. The app can do anything your key allows, not just chat.
  • Delete the key when you stop using the app.

AI coding assistants and agents

GitHub says one in three pull requests on its platform now involves an AI agent, and agents leak keys too. GitGuardian found 1,275,105 secrets for AI services exposed in 2025, up 81% on the year before. Commits co-authored by Claude Code leaked secrets at about twice the baseline rate.

The same report found 24,008 unique secrets in MCP configuration files, the files that connect AI agents to outside tools. A few habits keep agents safe:

  • Reference keys from environment variables in agent and MCP config files instead of typing them in. Claude Code, for example, expands ${API_NINJAS_KEY} in .mcp.json.
  • Keep config files that hold keys out of Git, and never paste a production key into a chat prompt.
  • Read the diff before you accept an agent's commit, and search it for anything that looks like a key.

What to do if your API key leaks

Assume a leaked key has already been copied, even if you deleted it seconds later. Bots scan public code around the clock, and slow clean-up is the norm: GitHub puts the average time to revoke a leaked secret by hand at about 40 days, and GitGuardian found that 64% of valid secrets it spotted in 2022 still worked four years later. Work through these steps in order:

  1. Replace the key now. Create a new key, or use the provider's rotate or change option, and disable the old one. Don't wait until you have cleaned up the leak.
  2. Update your apps. Put the new key in your environment variables or secrets store and redeploy.
  3. Remove the key from where it leaked. Delete the post, the paste or the file. If it was committed to Git, rewrite the history with a tool such as git filter-repo, and remember that forks and clones may still hold it.
  4. Check for misuse. Look at your usage dashboard and bill for calls you didn't make. If you see charges, contact the provider's support team.
  5. Fix the cause. Add the guardrail that would have stopped it: a .gitignore entry, push protection, a pre-commit scanner such as Gitleaks, or a server route instead of front-end code.

For API builders: how to issue keys safely

If you run an API yourself, a few design choices make your users' keys hard to leak and easy to recover:

  • Generate keys with a secure random source, at least 128 bits, such as Python's secrets module. Never derive them from user IDs or timestamps.
  • Show a new key once, then store only its hash. If your database is ever copied, a list of hashes is useless to an attacker.
  • Add a prefix, such as myapi_live_, so leak scanners can recognize your keys. A checksum at the end also lets you reject typos without a database lookup.
  • Let users create several named keys with their own permissions, and show when each one was last used.
  • Allow two active keys at once, so users can rotate without downtime.
  • Meter and rate-limit per key, and return clear 401, 403 and 429 errors.
  • Join GitHub's secret scanning partner program, so GitHub tells you when one of your keys turns up in a public repository.
keys.py
import hashlib import secrets def new_api_key(): key = "myapi_live_" + secrets.token_urlsafe(32) # 256 bits of randomness key_hash = hashlib.sha256(key.encode()).hexdigest() return key, key_hash # show `key` to the user once; store only `key_hash`

Frequently asked questions

Is an API key a password?

Not quite, but treat it like one. A password proves who a person is, while an API key identifies an app or account. Both are secrets, and anyone who has your key can use it as you.

Is an API key free?

Getting a key is usually free; using it may not be. Many APIs, including API Ninjas, have a free plan with a monthly quota, and charge for higher limits or commercial use.

Do API keys expire?

Most keys work until you delete or replace them, unlike OAuth tokens, which expire within hours. Some providers now disable old keys: since May 7, 2026, the Gemini API blocks unrestricted keys that have sat unused for a long time. Replacing keys on a schedule is good practice either way.

Can I share my API key?

No. Anyone with the key can use your quota and run up your bill, and you can't tell their requests from yours. Give each person or app its own key, or use the provider's team features.

Can I use one API key for several projects?

You can, but separate keys are safer. With one key per project, a leak in one place can be fixed without breaking the others, and usage reports show which project made which calls.

Is it safe to keep an API key in a private repository?

No. Private repositories get cloned, forked and shared with contractors, and GitGuardian found hardcoded secrets in 32.2% of internal repositories, against 5.6% of public ones. Keep keys in environment variables or a secrets manager.

Where should I store my API key?

In a .env file that Git ignores while you develop, and in a secrets manager in production, such as AWS Secrets Manager, Google Secret Manager or your hosting platform's environment settings. CI systems have their own encrypted secrets settings.

What is the difference between an API key and an API secret?

Some providers issue a pair. The key (sometimes called a client ID) says who you are and may be visible, while the secret proves it and must stay on your server. If you get only one value, treat it as the secret.

Can API keys be hacked?

A long random key can't realistically be guessed. Keys get stolen instead: from code pushed to GitHub, front-end JavaScript, logs, screenshots and support tickets. Following the habits above closes those gaps.

Is an API key for ChatGPT or Claude the same as my subscription?

No. The OpenAI and Anthropic APIs are billed separately from ChatGPT and Claude subscriptions, per request. A key lets apps use the API under your account, so set a spending limit before you paste it anywhere.