Most advice on how to get an API key stops at the wrong moment: open a dashboard, click Create key, and paste the result into your app. That gets you a credential, not a production-ready integration.

The work is deciding who owns the key, what it can access, where software can read it, and how you'll replace it without breaking unattended jobs. For agents and CLIs, there's another boundary: the tool needs the credential, but the conversation doesn't.

Table of Contents

What an API Key Commits You To

An API key can authorize requests and, with many providers, trigger billable activity. Before creating one, decide which application and environment it represents. A key named after its purpose is easier to audit than a shared credential called default.

Long-lived exposure is a practical concern. An analysis summarized by BleepingComputer found 543,699 unique credentials still valid in July, with a median public-accessibility period of 784 days. Creating the credential wasn't the difficult part; keeping control of it afterward was.

Which API Key Setup to Create

Use case Who owns it Restriction Where it lives
Public website Product project HTTP referrer list Server only, never a frontend bundle
Backend or server Service identity Egress IP allowlist Env var or secrets manager
Android app App project Package name and SHA-1 App config, not Git
iOS app App project Bundle identifier App config, not Git
CLI, CI, or agent Team or service identity Narrow API scopes; IP only if stable CI secret store or OS keychain
Separate dev and prod Same owner type, two keys Same restriction type, different values Different secret names; prod absent on laptops

Treat this table as a starting point, not permission to put a server secret in an app. Referrer restrictions apply to browser-facing APIs designed for public identifiers; a private backend key still belongs on the server. Likewise, mobile app configuration is extractable, so use only credentials the provider explicitly supports for that client.

For a backend, make the project and its access recoverable by the team. A service identity is preferable where supported, but some consoles require a human administrator to provision credentials. Don't solve that limitation with a shared personal password.

The creation button and the ongoing responsibilities are different jobs.

An infographic titled What an API Key Commits You To, comparing the ease of creation with ongoing responsibilities.

Choose the Owner Before the Credential

A traveling developer's CLI usually can't rely on a stable source address. Use narrow API permissions and controlled local storage rather than repeatedly weakening an IP restriction.

For teams connecting operational systems for the first time, VolunteerBadge's API integration basics for nonprofits provides useful context for deciding which application needs access.

Provisioning rule: If you can't identify an owner, a permitted caller, and a safe storage location, don't generate the key yet.

Create and Restrict the Key

Use the provider's official developer portal, not a dashboard URL copied from an unsolicited message. Console labels differ, but the workflow usually runs through Projects, APIs, and Credentials.

Google's API-key best practices support application restrictions, API restrictions, separate credentials, and header-based transmission. Those are useful defaults, but use the authentication mechanism documented for your particular endpoint.

Follow a Controlled Creation Sequence

  1. Sign in under recoverable team ownership. Use your organization's project and access controls for unattended workloads. The person clicking the button shouldn't become the only person capable of disabling the resulting credential.

  2. Select the project and enable the required API. Check the project selector before opening Credentials. A valid key in the wrong project won't enable a product that's switched off, and enabling unrelated APIs adds unnecessary access.

  3. Generate a dedicated, clearly named key. Use an application-and-environment name such as lead-enrichment-staging. Avoid reusing a working credential from another service just because it's already available.

  4. Apply restrictions before distribution. Set the appropriate caller restriction and limit the key to the API the integration needs. Configure billing and available quota controls too, but don't assume a billing alert is a hard spending stop.

  5. Save the credential and make a minimal request. Copy it directly into its intended secret store. For Google APIs that support the pattern, use the x-goog-api-key header or a client library rather than a URL query parameter.

  6. Verify both permission and rejection. Inspect the HTTP status, provider error code, request duration, and quota movement. Then attempt a request from a disallowed caller or against an API outside the permitted set.

The sequence below highlights the controls that should accompany creation, not merely the dashboard click.

A five-step infographic showing best practices for creating and securing an API key in a professional environment.

Test the Deployment, Not Just the Console

A successful console request proves less than a successful request from the deployed worker. The worker may leave through a different network, load a different secret, or use a different project.

Keep the test small and read-only where possible. Don't use a bulk enrichment job or a write operation to discover whether authentication works.

Record the result without recording the secret:

  • Allowed request: Note the operation, response status, and provider request identifier.
  • Denied request: Note which restriction caused rejection.
  • Quota behavior: Confirm the request appears under the intended project and credential.
  • Deployment identity: Confirm which service loaded the credential.

If a request fails, don't immediately remove restrictions to get a successful response. Correct the mismatch between the caller and the policy instead.

Credential creation should also account for eventual replacement. ThreatExploit AI's guide to rotating client API keys safely is a useful companion when planning that handover.

Store the Key Outside Git

Store the new credential in a secrets manager or inject it through an environment variable outside the source tree. Use distinct names such as PROVIDER_KEY_DEV and PROVIDER_KEY_PROD so deployment configuration makes the intended environment explicit.

A local dotenv file can work for development, but it's still a plaintext secret file. Keep it outside tracked content, restrict access, and commit only a template containing variable names and empty values.

Check Presence Without Revealing the Value

Don't use echo to debug a credential. In a POSIX shell, test -n "${PROVIDER_KEY_DEV:-}" checks whether a nonempty value exists without printing it; check the exit status rather than enabling verbose tracing.

Before pushing code, use a pre-commit secret scanner and repeat scanning in CI. Local hooks are convenient but bypassable, so they shouldn't be your only check.

  • Repository controls: Ignore local secret files before creating them, and scan staged changes.
  • Build controls: Inspect generated artifacts for accidental server-secret inclusion.
  • Logging controls: Redact authorization headers and disable request dumps containing credentials.
  • Human workflows: Keep values out of tickets, screenshots, chat messages, and copied terminal sessions.

An environment variable isn't a vault. Software running with sufficient access to the process can still read it, so give the credential only to workloads that need it.

Deleting a Line Doesn't Undo Exposure

A North Carolina State University study reported by ZDNET identified 201,642 unique API and cryptographic keys across more than 100,000 projects; 93.58% of detected credentials came from single-owner accounts. Individual developers need deliberate secret handling just as much as larger teams.

Git preserves historical commits. Removing the latest occurrence doesn't invalidate copies in earlier commits, forks, caches, or someone else's clone.

A repository cleanup changes where people can find a credential. Revocation changes whether they can use it.

Keep an ownership record alongside operational documentation, but never include the secret itself. Record the application, environment, permitted APIs, allowed callers, creation date, planned rotation date, and emergency revocation contact.

Set quota controls and billing alerts when the credential is provisioned. At looot, customers must keep API tokens private and remain responsible for all account or token use, including calls made by configured agents or scripts.

If the value is already in Git history, use the exposed-secret procedure under Rotate a Key Without Downtime. Revoke the credential rather than relying on another commit that deletes its text.

Fix a Key That Fails the First Call

Start by checking whether the API is enabled in the project that issued the key. A newly copied credential can be valid while the requested product remains unavailable.

Change a single setting, rerun the minimal request, and preserve the error response. Several simultaneous changes make it difficult to tell which assumption was wrong.

API Key Failures, Causes, and Fixes

Symptom Likely cause Fix
Auth error though the key was just copied API not enabled in this project Enable only that API and retest
Auth succeeds, provider refuses the call Billing or quota not set Attach billing, set a quota cap and an alert
Works in console, fails from the app IP, referrer, package, or bundle mismatch Use the restriction for this caller, or a separate dev key
Key appears in access logs Sent as a URL query parameter Send it in the provider header instead
New secret ignored Shell or CI still has the old value Update the secret store, restart, never print the value
Provider shows no request Secret never left the machine Check env inheritance and tool permissions
Request from an unknown IP Another script or a leak is using the key Revoke immediately and issue a replacement
Old key still succeeds after rotation Predecessor was hidden, not revoked Disable the old key in the console

These are diagnostic starting points, not universal error mappings. Providers classify failures differently, so read the response body and provider-specific error code rather than guessing from the status alone.

Separate Configuration Problems From Transport Problems

If the provider has no request record, inspect the client before editing permissions. A missing environment variable is possible, but so are a blocked connection, an incorrect endpoint, or a tool that never executed the request.

For a stale secret, restarting your terminal isn't necessarily enough. A running worker, background agent, or CI runner can retain the environment it received when it started.

Check the execution path:

  • Variable selection: Confirm the application reads the exact name you configured.
  • Process startup: Restart the process that sends requests.
  • Tool authorization: Confirm the agent has permission to invoke the integration.
  • Request routing: Verify the endpoint and project without dumping headers.

A production-restricted key failing on a laptop may indicate that the restriction works correctly. Test from the deployment environment or use a separate development credential.

For unfamiliar source addresses, distinguish documented deployment egress from unexplained activity. If the address remains unrecognized, treat the credential as compromised rather than widening its allowlist.

Finish troubleshooting with an allowed request and a deliberately disallowed request. A working integration with ineffective restrictions isn't a completed fix.

Pass a Key to an Agent or CLI

Getting an agent connected is the easy part. The production question is which process holds the credential, what the agent can invoke, and where requests are recorded. Keep the boundary clear: the execution layer authenticates; the conversation describes the job.

Never paste a provider key into a prompt and ask the agent to configure itself. Prompts and conversation history may be retained, and secrets can also end up in generated files, debugging output, or telemetry. Give the credential to the integration that makes the request, not to the model's conversation.

A diagram illustrating a security architecture with a human-run server key vault separated from an AI agent.

Prefer Login or Secret Injection

Use interactive login when the tool supports it, then check where its local token is stored and who can read it. Browser approval avoids copying a secret by hand, but the resulting token still needs protection.

To connect looot's MCP server to Claude Code, run:

claude mcp add --transport http looot https://api.looot.ai/mcp
claude mcp login looot

Sign in when the browser opens. The connection gives Claude Code access to looot's catalog through its MCP server. For unattended CI, use the runner's secret store instead of an interactive login. Keep committed MCP configuration limited to non-secret settings and runtime credential references.

The production security guidance recommends secure secret storage rather than placing keys in code or public repositories. Apply the same rule to generated code and configuration.

Make Environment Handling Explicit

Environment-variable precedence varies by tool. Some dotenv loaders preserve existing exports; others allow overrides. CI behavior also depends on the runner and application, so define and test which value wins.

  • Local execution: Load the development credential only into the process that needs it.
  • CI execution: Use the runner's secret mechanism and check for project-file overrides.
  • Child processes: Assume subprocesses may inherit exported variables.
  • Telemetry: Disable verbose traces that capture headers, environment dumps, or tool configuration.
  • Browser builds: Keep server-only variables separate from names the bundler exposes publicly.

For specialized integrations, the real estate agent skill setup offers a concrete reference for how a skill connects to its tools. Review installation instructions and credential permissions separately.

Agent boundary: Approving a tool doesn't mean approving every operation it can perform.

Before supplying provider credentials to a shared gateway, establish who can read them, where they persist, and which audit record identifies their use. looot's Bring your own key option connects your provider credentials; calls using them run at the provider's cost, with no looot markup.

After setup, test an operation the tool should allow and one it should refuse. Review the resulting logs for credential exposure without copying the credential into an inspection prompt.

Rotate a Key Without Downtime

For planned maintenance, rotate through a controlled overlap rather than deleting the working credential first. This requires a provider that permits replacement credentials to coexist.

Use this swap sequence when there's no evidence of compromise.

A four-step guide infographic for rotating a security key without causing system downtime.

Make the Replacement Observable

  1. Create the replacement. Give it a distinct name and reproduce the intended restrictions. Don't copy obsolete permissions just because the predecessor had them.

  2. Deploy and reload. Update the secret store, then restart or reload consumers according to how they read secrets. Include workers, scheduled jobs, CI, and agent tools.

  3. Verify actual use. Confirm successful requests, expected quota behavior, and rejected unauthorized requests. Where available, use credential-specific usage records to establish that traffic uses the replacement.

  4. Revoke the predecessor. Disable or delete it in the provider console, then verify that a controlled request using it fails authentication.

Google's rotation guidance recommends creating replacements, migrating applications, and deleting old keys. Keep the overlap bounded by an explicit completion check, not an intention to clean things up later.

A healthy server deployment doesn't prove the whole migration is finished. A scheduled task may not run during your initial validation window, so inventory consumers before revocation.

The following video provides an additional walkthrough of key rotation.

Compromise Changes the Order

If a credential appears in a repository, screenshot, ticket, or conversation, revoke first. Accept the service interruption if necessary; maintaining availability with a known exposed secret gives an unauthorized caller more opportunity to use it.

Afterward, issue the replacement through a clean path and investigate access records. Don't deploy it through the same leaking build or logging configuration.

Watch for these signals after the swap:

  • Authentication failures: A worker may still hold the predecessor.
  • Old-key success: Revocation may be incomplete, delayed, or applied to the wrong credential.
  • Unexpected volume: A consumer may be retrying aggressively or using the replacement incorrectly.
  • Unfamiliar locations: Investigate whether requests match your deployment.

Update the ownership record with the completed rotation and the next review date. Where the provider supports workload identity or short-lived credentials, consider those instead of maintaining another indefinitely valid secret.

Decide Between One Key and Many Accounts

If your application calls a single provider, stop with that provider's console and credential controls. Adding a gateway solely to avoid creating a key can introduce another dependency without solving a meaningful problem.

An agent that calls several data vendors presents a different trade-off. Separate accounts preserve direct provider control, but each integration adds credential handling, billing configuration, and a separate place to investigate failures.

Choose Based on Operational Responsibility

Before consolidating access, decide what you want to centralize:

  • Credential administration: Who provisions access and handles revocation?
  • Billing: Do you need separate vendor relationships or a shared balance?
  • Auditability: Can you identify the operation, provider, caller, and outcome?
  • Failure handling: Can you distinguish a gateway error from a provider refusal?

We built looot for the multi-provider case: an AI agent gets one API key and one prepaid balance for paid data APIs spanning web search, work emails, company data, and social profiles. You can use managed credits or bring your own provider key.

Setup takes about a minute: paste a line into your agent, approve in the browser, then ask for the job. That reduces connection work, but it doesn't transfer responsibility for the credential away from your team.

Complete a Small, Verifiable Deployment

Choose the direct provider connection or the shared access layer based on the workload you have. Don't provision extra credentials for integrations you haven't decided to run.

Make an authenticated request, verify an unauthorized operation is rejected, and record who can revoke access. Schedule the replacement before expanding the workflow to additional tools or autonomous jobs.


Visit looot if your agent needs a single connection to paid data APIs across providers, using managed credits or your own provider keys. Connect through browser approval, run a small authenticated job, and verify your credential boundaries before handing the workflow to an unattended agent.