AlgoMaster Logo

API Keys

High Priority13 min readUpdated September 13, 2026
Listen to this chapter
Unlock Audio

Some integrations need to run without a person signing in each time. A bookstore partner, for example, might synchronize its inventory every night through a job running on its own server. The bookstore needs a way to recognize the integration, limit what it can do, and stop its access if a credential leaks.

An API key can provide a straightforward credential for this kind of integration. The design becomes more demanding once several partners, environments, and deployments depend on it.

This chapter explains how keys identify callers, how to issue and verify them, and how to handle permissions, failures, rotation, and revocation.

The examples use a fictional bookstore's JSON API over HTTPS. Each partner runs its integration on a server it controls. The bookstore issues secret keys that identify a partner integration and stores the permissions separately. Key formats, permission names, and lifecycle rules below are application choices.

1. What an API Key Identifies

An API key is a value an API provider issues that a client includes in requests. Providers use that value in different ways. It may identify a project for usage accounting, authenticate an integration, or grant access through permissions associated with the key.

The name alone does not establish its security properties. Some products deliberately expose public keys in browser applications and use them only for limited operations or project identification. Other products issue secret keys whose possession grants substantial access. Read the contract for the specific key type.

In this bookstore, a secret key authenticates a partner integration. Successful verification might establish integration int_42, belonging to partner partner_17. It does not establish the identity of the employee who started the job, and it does not allow the integration to act as an arbitrary bookstore customer.

This is a bearer credential: anyone who obtains the complete value can present it. Copying the value is enough to impersonate the integration within the key's permissions. The key does not prove that a request came from a particular executable or machine.

A server-side inventory job is a reasonable fit when the partner can protect the secret and the permissions are narrow. User consent, interactive sign-in, and delegation to a third-party application require additional identity and authorization design. A shared partner secret cannot express which customer approved which access.

2. Key Boundaries and Permissions

Issuing one unrestricted key for an entire partner account is convenient at first. It also means a leak from a test script can affect production, and disabling one broken integration can interrupt unrelated jobs.

Give independently operated integrations separate credentials. Keep production and test credentials separate, and have the server enforce that isolation. A test prefix is a useful label, but the server must still reject a test key against production resources.

For this bookstore, the partner creates three integrations with different responsibilities:

Scroll
IntegrationEnvironmentPermissionsResource boundary
Catalog readerProductioncatalog:readBooks visible through the partner catalog
Inventory synchronizerProductioncatalog:read, inventory:writeInventory that partner_17 owns
Inventory test jobTestcatalog:read, inventory:writeTest inventory the test partner account owns

A permission names an operation the integration may perform. This API defines permission names such as inventory:write. They still need resource checks: the synchronizer may change its partner's stock, but cannot change a competing partner's stock by editing an ID in the URL.

The effective access should respect both the key's restrictions and the partner's current entitlement. If the partner loses access to inventory updates, a previously issued key must not preserve that access indefinitely.

Also define which identifiers you use to track usage. The bookstore records requests by key ID for troubleshooting and by partner ID for account-level limits. During rotation, two keys for one integration should not automatically double the partner's allowance. These accounting decisions are separate from whether the API authorizes a request.

3. Issuance and Storage

Key creation is a privileged operation. An authenticated partner administrator can create a key only for integrations they manage, and only with permissions they may grant. Allowing an inventory credential to mint unrestricted replacement credentials would defeat its restrictions.

Generate the secret with a cryptographically secure random number generator, which produces values that resist prediction. For this design, use 32 random bytes for the secret portion and encode them with URL-safe Base64. That gives 256 bits of randomness before encoding. This is an implementation choice, not a universal API-key requirement.

A key can contain a nonsecret lookup identifier and a random secret. For example, the illustrative value bk_live_k7M2_EXAMPLE_SECRET contains a provider prefix, an environment label, a key ID, and a placeholder secret. Every key value in this chapter is a placeholder and cannot authenticate.

The lookup ID lets the server find the key record without searching all stored secrets. The prefix helps operators recognize a credential type. Neither proves that the caller knows the secret or replaces verification.

For inbound verification, the bookstore stores a SHA-256 digest of the random secret rather than the recoverable secret itself. A digest is the fixed-size output of a cryptographic hash function. Hashing is appropriate here because the input is a randomly generated secret with enough possible values to resist guessing; human-chosen passwords need a password-hashing design that accounts for their much smaller guessing space.

Store metadata alongside the digest: key ID, integration ID, environment, permissions, creation and expiry times, and revocation status. A display name such as warehouse-nightly-sync helps administrators find the right key. Keep a separate record of administrative changes.

The issuance flow separates the partner's usable secret from the provider's verification record:

The provider shows the complete key once during creation. Later views expose metadata and the key ID. If the partner loses the secret, it creates a replacement. Key creation responses should prevent caching, and gateways and telemetry must redact the secret before recording request or response content.

The partner has a different storage requirement: its job must retrieve the usable key to send requests. Store that value in a secret manager or another protected secret store that only the workload can access. The provider's one-way verification storage does not eliminate the client's need to protect the original secret.

4. Request Verification

API keys have no single universal HTTP header convention. Some APIs define a dedicated header such as X-API-Key; others use an existing authentication scheme. The bookstore sends its opaque secret keys through the HTTP Bearer scheme and follows that scheme's challenge behavior. Using this header does not mean an OAuth flow issued the key or that the key contains a structured token payload.

The catalog reader requests a book as follows. HTTP/1.1 examples run over HTTPS, and content lengths count the exact single-line bodies these examples show without a trailing newline.

The bookstore chooses no-store for these partner responses. A header keeps credentials out of the URL, where they can appear in access logs and copied links. Logs can also capture headers, so configure redaction for the actual credential field throughout the request path.

Verification proceeds through several checks. Parse the credential using strict length and format limits. Look up its key ID, compute the supplied secret's digest, and compare digests using a constant-time comparison function. Such a function avoids ordinary early-exit comparisons that can reveal matching portions through execution time. It does not make database lookups or the entire endpoint take constant time.

Then check the record's environment, expiration, and revocation status, along with whether the integration remains enabled. Only a usable key establishes the integration context. The endpoint still evaluates the operation and resource permissions.

The diagram shows the successful path and separates credential validation from access policy:

Basic message parsing and size checks can happen earlier than this flow. Protected processing depends on a verified identity and the access checks the selected resource requires.

5. Failure Behavior

Predictable failures help partners distinguish a deployment secret problem from a denied operation or invalid data. They also keep internal credential records out of public error messages.

Unusable Credentials

This API returns the same credential failure for an unknown key, a key with an incorrect secret, an expired key, or a key the provider has revoked:

A 401 requires an applicable authentication challenge. For a request with no credential, the bookstore uses WWW-Authenticate: Bearer realm="bookstore-partners" without an error attribute. The bearer error name invalid_token applies to the presented credential even though the product calls it an API key.

Do not echo the submitted secret or disclose whether a guessed key ID exists. An authorized administrator can inspect expiry and revocation metadata through the management interface. A failing integration should report the problem to its operator rather than retry continuously with the same unusable key.

Insufficient Permissions

The catalog reader's key remains valid when it attempts an inventory write, but its permissions do not permit the operation:

This response tells the caller that the application denied permission. A new key with identical permissions would have the same result. The partner needs an appropriately authorized integration for the write.

Input rules remain separate. If the inventory synchronizer submits {"quantity":-1}, this API returns 422 because its quantity rule requires a nonnegative integer. The catalog reader receives 403 for the same operation regardless of quantity. If the synchronizer selects another partner's private inventory, the bookstore conceals it with a generic 404.

If the credential registry is temporarily unavailable and the API cannot verify a key, prevent protected processing and report an appropriate service failure, such as 503. An unavailable verifier does not establish that a credential is invalid.

6. Rotation and Revocation

Rotation replaces a credential with a new secret. Revocation disables a credential so it no longer grants access. Routine rotation should account for clients that update at different times.

For the bookstore's nightly synchronizer, use a bounded overlap period. Create a replacement with the intended permissions, store it in the partner's secret facility, update the job, and verify requests using the new key ID. Then revoke the old key. A concrete rotation window must include an actual run of the nightly job; ten quiet minutes tells you little about a workload that runs once a day.

This sequence lets the integration move between credentials while keeping the old key's lifetime limited:

The overlap is a planned availability trade-off. If you know a key has leaked, leaving it active also preserves the attacker's access. Revoke the compromised key promptly, deploy a replacement through a trusted channel, and inspect activity associated with the old key. Deleting a leaked value from a repository does not invalidate copies that already exist.

Define how quickly all servers must stop accepting a revoked key. If servers cache verification results for five minutes without invalidating them, a revoked key may still work at some servers during that interval. Use bounded cache lifetimes and an invalidation mechanism when the required response time demands it. Explain the actual enforcement delay to operators.

An expiry time provides a backstop, but scheduled jobs need advance notice and a tested replacement process. Record last-used time and usage by key ID to identify forgotten clients. Those records help with rotation; they cannot prove that no one has ever copied a credential that shows no recent use. Revocation also cannot undo requests that already completed.

7. Exposure and Operational Limits

Secret keys belong on systems that can keep them secret. Browser bundles, mobile applications, and distributed desktop binaries are available to their users. Obfuscation cannot turn an embedded shared secret into a reliable authentication boundary.

A browser application can call a backend that holds the partner key. That backend must authenticate its own users and enforce which operations they may request; otherwise it becomes an unrestricted way to exercise the hidden key's permissions. Public or publishable keys are appropriate only where the provider explicitly designs them for exposure and limits their authority accordingly.

Additional restrictions can reduce exposure. A stable server integration may restrict use to expected outbound IP addresses, provided address changes have an operational process. Such a restriction limits where the credential works; it does not identify the employee behind a request. Browser origin or referrer restrictions likewise do not turn a visible key into a secret credential.

Keep logs useful without storing secrets. Record key IDs, integration IDs, operation names, outcomes, and administrative changes under an appropriate retention policy. Redact credentials in application logs, gateway logs, traces, error reports, and support tools. Separate keys let an operator identify and disable one integration without interrupting every partner workload.

The resulting system has ongoing costs: issuing credentials, assigning owners, maintaining permission rules, replacing deployed secrets, and enforcing revocation across servers. API keys can keep a server integration straightforward when those responsibilities are explicit and the access they grant remains limited.

Summary

Define whether an API key identifies usage or serves as a secret credential, and specify which integration and permissions it represents. Keep secret keys on trusted servers, verify their values and current state, and enforce resource access independently of key validity.

Design the lifecycle alongside the request format: secure issuance, protected client storage, one-way server verification, bounded rotation overlap, and effective revocation. Separate credentials and useful metadata make failures easier to diagnose and compromised access easier to contain.