What Is an API Key, and Why Should You Protect It?

What an API key is, why anyone holding yours can spend your money, where it must never go, how to store and limit it, and what to do if it leaks.

Sooner or later, every guide to using an AI model from your own app or tool tells you to “create an API key” and then warns you, sometimes in red, never to share it. That warning can feel out of proportion for what looks like a random string of letters. It isn’t. The string is how the AI provider knows a request is yours, which decides whose account pays and whose limits get used up.

An API key is a secret code a provider issues to your account or project; your app attaches it to every request, and the provider checks it before doing any work [1, 2]. (An API is the published set of rules that lets one program ask another for something; a request is one such message.) Google Cloud describes its keys as a way to tie each request to a project “for billing and quota purposes” [3]. The key works for anyone who holds it, which is why OpenAI warns that a compromised one can mean unexpected charges, a drained quota, data loss and interrupted access [2]. The protective habits are few: keep the key on a server or in a tool’s credential store, give it only the access it needs, and know how to switch it off.

This guide closes the opening stretch of BuildAIQ’s path through AI APIs. What an AI API is sets the scene, and the previous guide, what happens during a single API request, follows the trip a key takes with every message. Keys are one part of keeping an app safe; protecting your users and the data they type is covered in BuildAIQ’s guide “How to Protect User Information in an AI App,” in the Building AI Applications series.

TL;DR

  • An API key identifies your account or project to an AI provider, which uses it to recognize your requests and decide who is billed and which limits apply [1, 3].
  • A key works for whoever holds it, so a leaked key can run up charges and use your quota or account data [2, 4].
  • Never put a key in browser or mobile app code, a web address, a code repository, a screenshot or a chat; route requests through your own server or tool instead [1, 5, 4].
  • Store keys in an environment variable, a secrets manager or a no-code tool’s credential feature, and give each key the least access it needs [2, 6, 7].
  • If a key leaks, switch it off or replace it right away (the guidance differs on which comes first), check usage and billing, and store the new key properly; deleting the file or commit is not enough [5, 8, 9, 10].

What an API Key Does

Your app sends the key in a header, a labeled line of information that travels with the request rather than inside the text you send the model. The web’s general mechanism for this is the Authorization header, which lets a program prove who it is to a server [11].

An illustrative example of that line, in which $AI_API_KEY stands for a stored key rather than a real one:

Authorization: Bearer $AI_API_KEY

Header names vary by provider and change. On Nov 22, 2026, Google’s Gemini API key page used an x-goog-api-key header and told developers to “treat your Gemini API key like a password” [5]. Anthropic’s documentation showed keys sent as Bearer credentials in the Authorization header and kept its older x-api-key header as a legacy option [12]. OpenAI’s API reference showed the same Authorization header [1]. These are examples, not endorsements; your provider’s current documentation decides its own format.

When the key is missing, mistyped or switched off, the provider refuses the request. In HTTP, the web’s messaging protocol, every response carries a status code, a number saying whether the request worked; 401 means the request “lacks valid authentication credentials” [11]; OpenAI, for one, documents a 401 error reading “Incorrect API key provided” [13]. Diagnosing other errors belongs to what to do when an AI API stops working.

Why a Leaked Key Is a Problem

A key is a bearer credential. The internet standard that defines bearer tokens (credentials of this kind, not the text tokens providers bill by) says any party holding one “can use the token in any way that any other party in possession of it can” [14]. Google Cloud applies the same idea to API keys, warning that someone who steals one of its authorization keys can authenticate as the service account it is bound to [4]. Unless you add restrictions of the kind described below, the key alone is enough [4, 14].

Providers spell out the consequences. OpenAI says a key exposed in a browser or mobile app lets malicious users make requests on your behalf, which “may lead to unexpected charges or compromise of certain account data” [2]. Google Cloud warns of unexpected charges and unauthorized access to your data [4]. Why usage turns into money is covered in how AI API pricing works.

Leaks are not rare. In a peer-reviewed study of public GitHub code collected in 2017 and 2018, researchers found leaked secrets in over 100,000 repositories, with thousands of new ones a day, and about 81% of the secrets they tracked were still in the current code roughly two weeks after discovery, while removed ones likely stayed reachable in Git history [15]. The data predate GitHub’s current safeguards and covered non-AI services, so read them as evidence that leaks are common, not as a current rate for AI keys.

Where a Key Must Never Go

Each rule follows from the bearer property: anyone who sees the key can use it.

In a website or mobile app

Code that runs in a browser or a phone app can be inspected by its users. Google’s Gemini documentation says keys compiled into client-side code “can be extracted by users” and recommends a backend proxy server to make the real API calls [5]. OpenAI says never to deploy a key in browsers or mobile apps and to route requests through your own back end, the server-side part of your app that users never see [2]. The layout behind this is explained in the parts behind an AI feature.

In a web address

Some services accept a key in the query string, the part of a link after the question mark. Avoid it. Google Cloud says a key in the URL is exposed “to theft through URL scans” and recommends the header instead [4]. The bearer-token standard gives the reason: browsers, servers and other software may keep web addresses in history and logs without protecting them [14].

In a code repository

A repository is a project’s code plus its full change history, tracked by tools such as Git and hosted by services such as GitHub. OpenAI calls committing a key to source code “a common vector for credential compromise” and notes that private repositories can leak too, in a breach [2]. Deleting the line later doesn’t undo the exposure: GitHub says committed secrets remain in history and can spread to forks, backups and logs, so the key must be revoked and replaced [8]. GitHub also lists quieter routes, including .env configuration files, real keys in example code, README files and wikis, and keys pasted into issues or pull request comments [8]. Britain’s NCSC, its national cyber security agency, puts the principle simply: keep secret credentials logically separate from source code [16].

In screenshots, chats, documents and shared workflows

The guidance above centers on code, but the logic covers anything other people can see. As BuildAIQ editorial guidance: don’t paste a key into a support chat, a team message, an AI chatbot, a shared document or a slide, and crop it out of screenshots and screen recordings. OpenAI’s reference is short on this point: “Don’t share it with others” [1]. Automation tools need the same care; n8n warns that request steps imported from a cURL command (a common text format for writing out a web request) may hold authentication headers that travel inside exported workflow files, and says to remove them before sharing [17].

Where to Keep a Key Instead

Environment variables. An environment variable is a named value set on your computer or server rather than inside your program [2]. Your code refers to the name, so the code can be shared without the key. Google’s and Anthropic’s software libraries read GEMINI_API_KEY (or GOOGLE_API_KEY) and ANTHROPIC_API_KEY automatically, and OpenAI recommends naming its variable OPENAI_API_KEY [2, 5, 12]. An illustrative line in macOS or Linux shell syntax, with a placeholder value and a neutral name you would swap for your provider’s:

export AI_API_KEY="YOUR_API_KEY"

Don’t type that line at the prompt with your real key in it: Bash writes typed commands to a history file when the shell exits, and Zsh does the same when a history file is set, leaving the key there in plain text [18, 19]. Google’s key page instead has you add an export line to the end of your shell’s startup file (~/.zshrc or ~/.bashrc), save it and reload, and gives separate Windows steps [5]. That file is plain text too, so keep it out of repositories and shared folders; how to make your first AI API request walks through the setup. If the variable isn’t set, your program has no key to send: depending on how it’s written, it either stops with a missing-key error or sends a request the provider rejects as unauthenticated [13, 11]. If you keep variables in a local .env file, list it in .gitignore, the file that tells Git what not to track, as GitHub recommends for files holding sensitive data [9].

A secrets manager. Anthropic tells developers to keep keys in a secrets manager, Google suggests a secret store such as Google Cloud Secret Manager for production, and OpenAI recommends a key management service for teams in production [2, 5, 12].

A no-code tool’s credential store. In a no-code or automation tool, enter the key in the connection or credentials feature, not in a text field or a hand-typed request header. n8n, one example, describes its credentials as “securely stored authentication information” for connecting workflows to services such as APIs; that is its own description [6]. The steps are in how to connect an AI API to a no-code tool.

Environment variables are a baseline, not a vault. OWASP, a nonprofit security community whose cheat sheets are community guidance rather than a standard, notes in its advice on running apps in containers that environment variables are generally accessible to all processes and may end up in logs or system dumps, and prefers other methods there where they’re available [10]. On your own laptop, one beats a key typed into code; once other people use your app, a secrets manager is the next step [2, 5, 12].

Give Each Key as Little Power as Possible

Security professionals call this least privilege, which the computer security glossary of NIST, a US standards agency, defines, quoting federal security publications, as restricting access to “the minimum necessary to accomplish assigned tasks” [7].

  • One key per app and per person. Google Cloud recommends a separate key for each team member and application, which keeps an audit trail and limits the damage from a compromise [4].
  • Scope and permissions. On OpenAI’s platform, a personal key created in a project is scoped to that project, and in late November 2026 user-owned keys could be set to All (the default), Restricted to chosen endpoints (the specific web addresses for individual API functions), or Read Only [20]. Google says restrictions reduce the impact of a compromised key, and Google Cloud calls unrestricted keys insecure [4, 3]. As of Nov 22, 2026, Google’s Gemini page said the Gemini API rejects requests from unrestricted standard keys and that new keys created in Google AI Studio since May 28, 2026 are authorization keys bound to a service account [5].
  • Separate test and live keys. OpenAI suggests separate projects for staging and production, each with its own access, rate and spend limits [21].
  • Expiration dates. OpenAI lets project keys carry an expiration date and recommends using one [2]. Anthropic, as of late November 2026, offers presets from 3 hours to 30 days, a custom length or no expiry, and says expiration “is not a substitute for secret hygiene” [12].
  • A spending ceiling. OpenAI recommends monthly spend limits with hard enforcement to help limit costs from a leaked key; it notes that alerts alone don’t stop traffic and that enforcement isn’t instantaneous, so spending can slightly exceed the limit [2]. Which controls stop spending and which only notify is covered in how to avoid unexpected AI API charges.

Rotating and Revoking Keys

Revoking a key switches it off for good. Rotating means replacing it on purpose; Google Cloud describes creating a new key, updating your apps and deleting the old one [4]. OWASP’s case for doing this regularly is that stolen credentials then only work for a short time [10].

For planned rotation, providers describe an order that keeps your app running. OpenAI advises creating the replacement, updating your applications and revoking the old key once the new one works [2]. Microsoft gives each Foundry Tools resource two keys for this reason: move every app to one key, regenerate the other, switch over, then regenerate the first, bearing in mind that a regenerated key stops working at once and apps still using it get 401 errors [22].

On OpenAI’s platform, switching off is fast: revocations take effect within a few seconds, while most other changes affecting a key propagate within 15 minutes but can take longer [1]. Anthropic’s console separates a reversible Disable from a permanent Delete [12].

If Your Key Leaks: A Checklist

A hypothetical example: a student pastes a key into a class-project script and pushes it to a public GitHub repository. GitHub may block that push, because push protection for personal accounts is on by default and stops detected secrets from reaching public repositories [23]. If the key gets through, GitHub’s free secret scanning of public repositories alerts providers in its partner program so they can act, for example by revoking the key [24]. Neither safeguard catches every key, so the student should act at once.

The steps below are BuildAIQ editorial guidance assembled from the cited provider and security guidance:

  1. Deal with the key right away. Revoke, disable or rotate it in the provider’s dashboard; GitHub and OpenAI say to revoke or rotate a leaked key immediately, and OWASP lists immediate revocation first [2, 24, 9, 10]. With no users waiting, as in a class project, switching it off before the replacement is ready costs little; a live app may need the replacement in place first, the order Google’s Gemini page gives [5].
  2. Check usage and billing. Look for requests you didn’t make; OpenAI suggests reviewing usage, and Google’s Gemini page says to audit billing logs and API usage [2, 5].
  3. Issue a new key and store it properly, in an environment variable, secrets manager or credential store, with only the permissions it needs [2, 20].
  4. Clean up where it leaked. Remove the key from the code or document and add the secrets file to .gitignore [9]. Rewriting Git history to erase it has limits: GitHub says copies can survive in clones, forks and cached views, and that revoking the key may be enough [9].
  5. Add safeguards for next time: keep push protection on, set a spending limit and consider expiration dates on new keys [2, 12, 23].
  6. Contact the provider if you see misuse; OpenAI points users worried about a leaked key to its help center [2].

What We Know, What We Don’t, and Where Experts Disagree

What We Know

The providers and security bodies cited agree on the basics: keep keys out of client-side code, URLs and repositories, store them outside the code, limit each key’s reach, and revoke a leaked key rather than only deleting it [2, 5, 4, 12, 8, 10, 16].

What We Don’t Know

We found no current, independent figures on how often AI-provider keys are stolen or what misuse typically costs; the only measured study here used 2017 and 2018 data on other services [15]. Detection features such as GitHub’s scanning and Google’s leaked-key enforcement for its authorization keys are described by the companies themselves, not by independent tests [5, 24].

What Experts Disagree About

Two named organizations recommend opposite orders for the same situation. OWASP’s cheat sheet, which puts rapid containment first, lists immediate revocation of an exposed key before creating a replacement [10]. Google’s Gemini page, aiming to avoid application downtime, says to create and deploy a replacement first and disable the leaked key only once the new one is verified [5]. GitHub and OpenAI say to act immediately without settling the order [2, 24, 9]; step 1 of the checklist above says when each order fits.

Practical Takeaways

  • Treat an API key like a password tied to your bill: keep it out of code, chats, screenshots and shared files.
  • Keep every request that needs the key on a server or inside a tool’s credential feature, never in a web page or phone app.
  • Start with an environment variable and a .gitignore entry; move to a secrets manager before other people rely on your app.
  • Create separate keys for each project and for testing versus live use, with the narrowest permissions your provider offers.
  • Set an expiration date and a spending limit where your provider supports them, and note when you last rotated each key.

Sources

  1. API Overview (OpenAI API reference). OpenAI, accessed 2026-11-22.
  2. Best practices for API key safety. OpenAI Help Center, accessed 2026-11-22.
  3. Manage API keys. Google Cloud, 2026-11-17, accessed 2026-11-22.
  4. Best practices for managing API keys. Google Cloud, 2026-11-17, accessed 2026-11-22.
  5. Using Gemini API keys. Google (Google AI Studio documentation), accessed 2026-11-22.
  6. Create and edit credentials. n8n, accessed 2026-11-22.
  7. least privilege (glossary term). NIST Computer Security Resource Center, accessed 2026-11-22.
  8. Secret leakage risks. GitHub Docs, accessed 2026-11-22.
  9. Removing sensitive data from a repository. GitHub Docs, accessed 2026-11-22.
  10. Secrets Management Cheat Sheet. OWASP Cheat Sheet Series, accessed 2026-11-22.
  11. RFC 9110: HTTP Semantics. IETF (RFC Editor), 2022-06, accessed 2026-11-22.
  12. Authentication (Claude API). Anthropic, accessed 2026-11-22.
  13. Error codes. OpenAI, accessed 2026-11-22.
  14. RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage. IETF (RFC Editor), 2012-10, accessed 2026-11-22.
  15. How Bad Can It Git? Characterizing Secret Leakage in Public GitHub Repositories. Network and Distributed System Security (NDSS) Symposium 2019, 2019-02, accessed 2026-11-22.
  16. Secure development and deployment guidance: Protect your code repository. UK National Cyber Security Centre (NCSC), 2019-02-20, accessed 2026-11-22.
  17. Export and import. n8n, accessed 2026-11-22.
  18. Bash History Facilities (Bash Reference Manual, section 9.1). GNU Project (Free Software Foundation), accessed 2026-11-22.
  19. 15 Parameters (zsh manual). Zsh project (zsh.sourceforge.io), accessed 2026-11-22.
  20. Managing projects in the API platform. OpenAI Help Center, accessed 2026-11-22.
  21. Production best practices. OpenAI, accessed 2026-11-22.
  22. Rotate keys in Foundry Tools. Microsoft Learn, 2026-06-05, accessed 2026-11-22.
  23. Push protection. GitHub Docs, accessed 2026-11-22.
  24. Secret scanning. GitHub Docs, accessed 2026-11-22.