Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Short answer: treat every API key as a bearer credential. Give it only the APIs, operations, resources, origins, and IP ranges it needs; keep it in a managed secret store rather than code or URLs; use short-lived identity-based credentials when available; rotate with an overlap period; and monitor, rate-limit, and revoke quickly. An API key by itself is not sufficient protection for high-value data or administrative endpoints.

Public exposure can enable unauthorized use and unexpected charges. Google Cloud states that “Unrestricted API keys are insecure” and warns that exposed keys can lead to unauthorized data access or charges (Google Cloud; Google Cloud best practices).

What an API key does—and what it does not do

An API key usually identifies an application, project, or account for quota and billing. It is normally a bearer credential: whoever possesses the value can present it. A standard Google API key does not authenticate a human or service principal. Google’s separate authorization keys bind to a service account and behave like long-lived access tokens; Google cautions against using them in production for APIs that create or manage resources (Google Cloud).

That distinction matters when choosing controls. A key can restrict where a request comes from and which APIs it may call, but it generally does not prove which end user initiated the request. Do not rely on a key alone to authorize a transfer, expose private records, change account settings, or perform another high-impact action. Add user or workload authentication, authorization checks, and server-side policy for those operations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the right credential model

Compare the available mechanisms across six dimensions before creating a key:

Dimension Standard API key Service-account or IAM credential Federated or short-lived credential
Identity strength Associates a request with a project or application, not necessarily a principal Identifies a workload or service account Identifies a user or workload through an external identity provider
Privilege granularity Often API, application, and sometimes IP or origin restrictions Usually supports roles, scopes, resources, and conditions Can apply temporary roles, scopes, and policy conditions
Lifetime Often long-lived until replaced or deleted May be long-lived unless issued through a token service Short-lived by design
Application or network limits Commonly available through referrer, app, IP, or API restrictions Usually enforced with IAM and network policy Enforced by identity, claims, and policy conditions
Auditability and revocation Logs show key or project usage; revocation is key deletion Logs can identify the service account and role Individual sessions or tokens can expire quickly
Operational burden Simple to issue, but requires careful storage and rotation More setup, with stronger control Highest integration effort, lowest standing-secret exposure

Prefer IAM, workload identity, federation, or short-lived credentials when the platform supports them (Google Cloud; AWS IAM best practices). Use a conventional API key for low-risk identification, public-but-metered APIs, or services that do not offer stronger identity—not as a substitute for authorization.

Restrict permissions to the minimum

Inventory before changing anything

For every key, record an owner, application, environment, allowed APIs, allowed methods, permitted resources, origins or IP ranges, creation date, expiry or review date, and the system that stores it. A key without an owner or usage purpose is a candidate for retirement. This inventory also exposes privilege creep: permissions added for a temporary migration often remain after the migration ends.

Apply API and application restrictions

  1. Limit the API surface. Enable only the specific APIs or products the consumer calls. Reject unrestricted keys wherever the provider offers an organization policy or preventive control.
  2. Limit operations and resources. Choose read-only scopes when writes are unnecessary, restrict methods such as list or create, and bind access to named projects, buckets, queues, tables, or records where supported.
  3. Constrain the caller. For browser keys, use exact HTTPS origins and separate keys by site. For server workloads, use fixed egress IPs or private networking when practical. Mobile applications cannot keep a secret reliably, so treat an embedded key as public and enforce server-side limits.
  4. Set conditions and expiry. Add time, environment, network, or device conditions and an expiration date if the provider supports them. A temporary key should not become a permanent credential.
  5. Test the negative cases. Verify that an unauthorized API, method, origin, resource, and environment each fail. A permission test that checks only the happy path misses overbroad access.

Grant the minimum scopes and permissions, then review them periodically. GitHub recommends selecting only the minimum permissions or scopes and setting the shortest practical expiration for a personal access token (GitHub credential security). OWASP’s authorization guidance likewise recommends least privilege and explicit, server-side authorization checks (OWASP Authorization Cheat Sheet).

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Store and transmit keys safely

Use a secret manager, not source code

Keep production values in a managed secret store or an encrypted CI/CD secret facility. Grant read access only to the workload that needs the secret, audit reads, and separate development, staging, and production values. GitHub recommends secret scanning and removing exposed credentials from repositories (GitHub credential security).

  • Never commit a key to Git, a container image, a package, a front-end bundle, or a configuration file distributed to customers.
  • Do not paste keys into tickets, chat, screenshots, crash reports, or unencrypted email.
  • Do not put a key in a URL unless the provider explicitly requires that form; URLs are commonly retained in browser history, proxy logs, analytics, and referrer headers. Google specifically advises using approved headers or SDK mechanisms instead of query strings when possible (Google Cloud best practices).
  • Prevent shell history and process listings from capturing secrets. Prefer an environment variable or secret-injection mechanism over typing a literal value in a command.

Send only the approved credential format

Follow the provider’s documented header or SDK method exactly. A server should load the secret at runtime, use TLS, and avoid logging request headers. Redact authorization values in application, gateway, and tracing logs. If a provider requires a query parameter, isolate that call, suppress command logging, and ensure access logs are scrubbed.

Rotate keys with overlap, not downtime

There is no universal safe number of days for rotation. The right cadence depends on exposure risk, provider limits, and how quickly every consumer can be updated. Rotate immediately after suspected exposure, personnel or vendor changes, or an unexplained usage anomaly. Otherwise, set a review and expiration policy appropriate to the environment; short-lived credentials should be preferred for workloads that support them.

  1. Discover consumers. Use the inventory, code search, deployment manifests, secret-store access logs, and provider usage reports to find every caller.
  2. Issue a replacement. Give the new key exactly the old key’s required permissions—or fewer—and apply the same application restrictions.
  3. Deploy the replacement. Update the secret store or runtime configuration without printing the value. Keep the old key valid for a defined overlap window long enough for rolling deployments and queued jobs to complete.
  4. Verify. Exercise representative reads and writes, check error rates and usage logs, and confirm that every environment is using the replacement.
  5. Revoke and remove. Delete or disable the predecessor, remove dormant copies, and update the inventory with the new owner, creation date, and next review.

Google documents this overlap-and-replace pattern and recommends deleting unused keys (Google Cloud best practices; Google API key guidance).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Monitor use and prepare for compromise

Collect key or principal identifiers, API method, resource, timestamp, response code, source location, latency, quota, and spend where the provider exposes them. Alert on new countries or networks, sudden volume, unusual methods, repeated authorization failures, quota exhaustion, and spend outside the normal pattern. Apply per-key and per-client rate limits and return HTTP 429 when a caller exceeds policy (OWASP REST Security Cheat Sheet).

Your breach playbook should be executable without waiting for an investigation:

  1. Identify the exact key and disable or revoke it.
  2. Issue a replacement and rotate any dependent secrets.
  3. Inspect logs, quotas, source locations, methods, and billing for the period of possible exposure.
  4. Determine whether data was read, changed, or deleted; preserve evidence and notify the responsible owners.
  5. Close the exposure, add a preventive restriction, and document the incident.

OWASP notes that credentials issued to third-party clients are relatively easy to compromise, so detection and revocation are part of the control—not optional extras (OWASP REST Security Cheat Sheet).

A safe request pattern in code

The following pattern keeps a secret outside the source tree and supplies it at runtime. Replace the provider-specific endpoint and header name with the documented values for your service; do not paste a real key into these examples.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Shell and cURL

export API_KEY='loaded-by-your-secret-store'
curl --fail-with-body --silent --show-error 
  -H "Authorization: Bearer $API_KEY" 
  -H 'Accept: application/json' 
  "$API_BASE/resource"

Python

import os
import requests

key = os.environ['API_KEY']
base = os.environ['API_BASE']
response = requests.get(
    f'{base}/resource',
    headers={'Authorization': f'Bearer {key}', 'Accept': 'application/json'},
    timeout=30,
)
response.raise_for_status()
print(response.json())

Node.js

const key = process.env.API_KEY;
const base = process.env.API_BASE;
if (!key || !base) throw new Error('API_KEY and API_BASE are required');
const res = await fetch(`${base}/resource`, {
  headers: { Authorization: `Bearer ${key}`, Accept: 'application/json' }
});
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
console.log(await res.json());

Do not log the full request object, headers, or exception objects that may contain them. Add automated tests that assert the key is absent from repository history, build artifacts, URLs, and logs.

Applying the model to a screenshot API key

If a server needs to call ScreenshotNeo, keep the access key in your secret manager and inject it as YOUR_API_KEY at runtime. ScreenshotNeo documents its API at https://screenshotneo.com/docs/. The service accepts the access key as the access_key parameter, so protect command history and URL logs when using these examples.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server for developers. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response reports the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Every plan includes the full feature set, including full-page capture with lazy-image loading, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF controls, HTML/CSS rendering, custom CSS and JavaScript, click-before-capture, selector hiding, selector or network-idle waits, request and resource blocking, custom headers and cookies, user-agent, authorization, timezone and geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Existing integrations can use the parameter names common to other screenshot APIs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free. Create a free ScreenshotNeo account to get started.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

Requests suddenly return 401 or 403

Check that the runtime loaded the replacement key, the authorization scheme matches the provider, and the key still allows the API, method, resource, origin, and IP. Compare deployment timestamps with the rotation window; a revoked predecessor or an omitted permission is more likely than a transport problem.

Requests work locally but fail in production

Verify that production has its own secret-store entry, network egress is within the allowed range, and the production key is not being replaced by a development variable. Check clock and TLS configuration if the provider uses signed or time-bound credentials.

The provider reports quota or spend spikes

Search logs for unusual methods and source locations, apply rate limits, and revoke the key if the activity is unexplained. Do not wait for a monthly invoice; preserve logs and follow the breach playbook.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A key was committed to a repository

Assume compromise. Revoke it first, then remove it from the repository and history, rotate dependent credentials, inspect usage, and enable secret scanning to prevent recurrence. Deleting the file alone does not invalidate copies already cloned or indexed.

Rotation caused intermittent errors

The old key was probably revoked before all consumers updated, or a worker retained a cached configuration. Re-enable only if policy permits, deploy the replacement everywhere, verify traffic, then revoke the predecessor after the documented overlap period.

Frequently Asked Questions

Should a public browser key ever be considered secret?

No. Any value shipped to a browser, mobile package, or other untrusted client can be extracted. Treat it as public, restrict its origins and APIs, enforce server-side authorization, and avoid granting write or administrative permissions.

What should I record for an API-key review?

Record the owner, consumer, environment, allowed APIs and resources, application or network restrictions, creation and expiry dates, secret-store location, last observed use, and the planned replacement or retirement date.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can rate limiting replace permission restrictions?

No. Rate limits reduce volume but do not stop an overprivileged caller from accessing an allowed resource. Use least-privilege permissions first, then rate limits and anomaly detection as additional controls.

How can I prove a rotated key is no longer used?

Use provider usage logs, secret-store access logs, deployment records, and a period of normal traffic after the replacement. A zero-use interval is evidence, not proof, if dormant jobs or rarely used paths are not included in testing.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.