APIs: Concepts, Design, Requests, Responses, and Integration

API Credentials

Learn what API credentials are, how authentication differs from authorization, how to send credentials securely, and how to troubleshoot common API access errors.

API credentials are identifiers or secrets that an API uses to identify and authenticate an application, user, or service. They allow an API provider to decide whether a request may proceed and what that request is allowed to do.

This lesson covers common credential types, where to send them, how to store them safely, how client-side and server-side usage differ, and how to diagnose authentication failures.

Why APIs Require Credentials

An API is a controlled interface to data or operations. Without access controls, anyone could read private information, change resources, consume expensive services, or overwhelm the system.

Credentials help an API provider:

  • Verify the identity of the caller.
  • Determine which operations the caller is authorized to perform.
  • Track usage by application, user, project, or service.
  • Apply rate limits and quotas.
  • Associate usage with billing accounts where applicable.
  • Detect and prevent abuse.

Authentication versus authorization

Authentication means verifying who or what is making a request. For example, an API may verify that an access token belongs to a particular user or application.

Authorization means determining what an authenticated caller is allowed to do. A valid token might identify a user but still lack permission to delete a resource.

A useful sequence is: authentication answers “Who are you?”; authorization answers “What may you do?”

Common API Credential Types

Each API defines its own credential format, header names, token schemes, and lifecycle. Never assume that a pattern used by one provider works with another.

API Credential Types

API key — Typical use: simple application or project identification. Where sent: a provider-defined header, such as X-API-Key, or sometimes a query parameter. Sensitivity: usually sensitive, even when restricted. Expiration or rotation: rotate periodically and immediately after exposure.

Bearer token — Typical use: presenting an access token to a protected API. Where sent: the Authorization header. Sensitivity: high; whoever possesses it may use it. Expiration or rotation: commonly short-lived; refresh or replace when expired.

OAuth client ID — Typical use: identifying an OAuth application during an authorization flow. Where sent: authorization requests or token requests, according to the provider. Sensitivity: generally publishable, although provider restrictions still apply. Expiration or rotation: usually stable, but may be regenerated.

OAuth client secret — Typical use: authenticating a confidential OAuth application to an authorization server. Where sent: a token endpoint request, as documented by the provider. Sensitivity: highly confidential. Expiration or rotation: rotate periodically and after suspected exposure.

Basic authentication — Typical use: a username and password encoded for an HTTP request. Where sent: the Authorization header. Sensitivity: highly confidential. Expiration or rotation: change passwords and use HTTPS.

Session cookie — Typical use: maintaining a browser-based authenticated session. Where sent: a cookie automatically included by the browser. Sensitivity: high; possession may enable session use. Expiration or rotation: expire sessions and invalidate them during logout or incident response.

Signed request or HMAC credential — Typical use: proving that a request was created by a holder of a shared secret and was not altered. Where sent: signature and related values in headers or query parameters, as specified by the API. Sensitivity: the signing secret is highly confidential. Expiration or rotation: use timestamps or nonces to limit replay, and rotate the secret.

Service-account credential — Typical use: server-to-server access without an interactive user. Where sent: an access token, signed assertion, or provider-specific request. Sensitivity: highly confidential, especially private keys. Expiration or rotation: prefer short-lived credentials and rotate keys.

Where Credentials Are Sent

Authorization headers

Bearer and Basic authentication commonly use the standard Authorization header:

Authorization: Bearer <access-token>

For Basic authentication, the value has a provider-defined encoding of a username and password:

Authorization: Basic <encoded-credentials>

A bearer token is accepted from whoever presents it, so protect it like a password.

Custom API-key headers

Many APIs use a custom header. The header name and value format are provider-specific:

X-API-Key: <api-key>

Query parameters

Some APIs accept credentials in a URL query parameter, such as ?key=<api-key>. This is generally discouraged for secrets because URLs can appear in browser history, proxy records, analytics systems, logs, and error reports. Use a header when the API supports one.

Request bodies

Credentials belong in a request body only when an authentication endpoint explicitly requires that format, such as a token endpoint accepting form fields. Do not put credentials in arbitrary resource request bodies unless the API documentation specifies it.

Cookies

Browser-based sessions may send credentials as cookies. Cookies should use appropriate security attributes such as Secure and, where suitable, HttpOnly and SameSite. Follow the provider's session and cross-origin requirements.

Obtaining and Managing Credentials

  1. Register an application, project, or service through the API provider's developer portal.
  2. Create a key, OAuth application, user token, or service account.
  3. Associate the credential with the correct application, environment, user, or service account.
  4. Assign only the scopes, roles, and resource permissions required.
  5. Record its owner, purpose, environment, creation date, and expiration policy in protected operational documentation.
  6. Store it in protected configuration rather than in application source code.
  7. Monitor usage and establish a rotation and revocation procedure.

A scope is a defined set of permissions requested or granted to a token or application. A role may provide a broader provider-defined collection of permissions. Use both scopes and roles to enforce least privilege.

Use separate credentials by environment

Development, testing, staging, and production should normally use different credentials. This prevents test activity from changing production data and limits the damage if a local or test credential is exposed.

Credential Storage by Environment

Local development — Recommended storage: environment variables or a local secret file excluded from version control. Allowed credential type: development key or short-lived developer token. Notes: use test data and never print the complete value.

Testing — Recommended storage: CI/CD encrypted secrets or a test secret manager. Allowed credential type: test-only key or service account. Notes: restrict access and use disposable resources where possible.

Staging — Recommended storage: deployment platform secret store or centralized secret manager. Allowed credential type: staging-specific service credential. Notes: match production configuration without sharing production secrets.

Production — Recommended storage: managed secret manager or encrypted hosting configuration. Allowed credential type: narrowly scoped production credential. Notes: restrict operators, audit access, set expiration, and plan rotation.

Expiration, rotation, and revocation

Credential rotation is replacing a credential periodically or after suspected exposure. Revocation is invalidating a credential so it can no longer be used.

A safe replacement process is to create the new credential, deploy it, verify requests, then revoke the old credential. During an incident, revoke the exposed credential immediately if possible, even if replacement deployment has not finished.

Secure Credential Handling

  • Treat client secrets, passwords, private keys, and long-lived tokens as sensitive data.
  • Store secrets in environment variables, secret managers, or protected deployment configuration.
  • Do not hard-code real secrets in source files.
  • Do not place secrets in frontend bundles, public examples, screenshots, logs, error reports, or version-control repositories.
  • Use HTTPS for every authenticated API request.
  • Apply least privilege: grant only the permissions required for the task.
  • Use short-lived tokens where the provider supports them.
  • Restrict keys by project, host, IP range, origin, operation, or environment when supported.
  • Rotate any credential that is exposed or suspected to be compromised.

A secret manager is a secure system for storing sensitive configuration values, controlling access to them, and supporting rotation. It is preferable to distributing long-lived secrets through chat, email, source code, or manually copied configuration files.

Client-Side versus Server-Side Credentials

Frontend code runs on a user's device and can be inspected. Users can view JavaScript bundles, network requests, browser storage, and configuration values delivered to the browser. Therefore, a credential placed in frontend code should be considered visible to users.

Confidential credentials must remain on trusted backend infrastructure. The backend can load a secret, call the third-party API, and return only the data the frontend needs.

Backend proxy pattern

  1. The browser sends a request to your backend.
  2. The backend authenticates the user and validates the requested operation.
  3. The backend loads the server-only API credential from protected configuration.
  4. The backend calls the external API over HTTPS.
  5. The backend filters the response and returns an appropriate result to the browser.

A provider may explicitly support publishable or restricted client-side keys. Such a key is not a secret merely because it is called a key; it should still be restricted by origin, operations, quotas, or project. Never put an OAuth client secret, private key, password, or unrestricted long-lived token in a browser bundle.

Making Authenticated Requests

The exact header name, token scheme, and credential format come from the API documentation. The following examples use placeholders only.

Bearer-token request

curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/v1/resource

The server reads an access token from the Authorization header. An access token is usually time-limited and grants access to protected resources. The Bearer scheme means the server authorizes the holder of the presented token.

API-key request

curl -H "X-API-Key: $API_KEY" https://api.example.com/v1/resource

This pattern is valid only when the provider documents X-API-Key. Another API may require a different header such as Api-Key or a completely different mechanism.

Load a secret from the environment

export API_TOKEN='replace-with-local-development-token'

Application code should read API_TOKEN or API_KEY from the process environment before constructing the request. The example value is a placeholder, not a real credential.

token = process.env.API_TOKEN

In production, configure API_TOKEN in the hosting platform's encrypted secret store. Do not place it in client-side build variables unless the provider documents that value as publishable.

Verifying authentication

A successful response status does not always prove that every permission is correct, but it indicates that the request passed the relevant checks for that operation. Inspect the status code and structured response body without logging credential values.

  • 2xx: the request was generally accepted or completed.
  • 401: the server could not authenticate the request.
  • 403: the identity may be valid, but the operation is not permitted.
  • 429: a rate or quota limit was exceeded.

Authentication Failures and Operational Troubleshooting

Authentication Response Troubleshooting

401 Unauthorized — Likely cause: missing, malformed, invalid, or expired credential; wrong header name or authentication scheme. Safe checks: confirm the documented header and prefix, check that the environment variable exists without printing its value, and verify HTTPS. Recommended resolution: correct the request format or refresh and replace the expired credential.

403 Forbidden — Likely cause: valid identity but insufficient scope, role, project access, or resource permission; IP, origin, referrer, or network restrictions. Safe checks: review scopes, roles, resource ownership, project selection, and access restrictions. Recommended resolution: grant only the required permission or correct the configured restriction.

429 Too Many Requests — Likely cause: the credential or account exceeded a rate or quota limit. Safe checks: inspect documented response headers and provider quota information without exposing credentials. Recommended resolution: reduce unnecessary requests, use documented retry behavior with backoff, and review quota or billing settings.

Provider-specific error — Likely cause: an API-specific policy, parameter, audience, issuer, signature, or account problem. Safe checks: read the provider's error code and request identifier, then compare the request with current documentation. Recommended resolution: follow the provider's documented correction while keeping secret values redacted.

Safe debugging practices

  • Log the status code, endpoint path, method, timestamp, and provider request ID when available.
  • Redact authorization headers, API keys, cookies, passwords, private keys, and token values.
  • When checking an environment variable, log only whether it is present and perhaps its non-sensitive metadata, never the full value.
  • Use a token fingerprint or last few characters only when an approved diagnostic process requires correlation.
  • Reproduce failures with test credentials and test data where possible.
  • Do not paste complete requests containing secrets into tickets, chat, screenshots, or public issue trackers.

Responding to an exposed credential

  1. Assume the credential is compromised.
  2. Revoke it immediately through the provider dashboard or API.
  3. Create a replacement with the minimum required permissions.
  4. Update protected deployment configuration and restart affected services if necessary.
  5. Inspect usage and access logs for suspicious activity.
  6. Remove the exposed value from source, public bundles, documentation, and other accessible locations. Removing it from the latest commit does not make the old value safe; revocation is essential.
  7. Identify how the exposure happened and add preventive controls such as secret scanning, repository rules, or deployment checks.

Exam-Relevant Notes

  • Authentication verifies identity; authorization determines permissions.
  • A bearer token must be protected like a password because possession may be enough to use it.
  • Client IDs can be public in OAuth, but client secrets must stay on confidential backend systems.
  • Query-string credentials are generally discouraged because URLs are commonly logged and retained.
  • 401 usually indicates an authentication problem; 403 usually indicates an authorization or access-policy problem.
  • 429 indicates rate limiting or quota exhaustion, not necessarily invalid credentials.
  • HTTPS protects credentials while they travel between client and server; it does not protect a secret that is already exposed in frontend code or a repository.
  • Separate environment credentials and least privilege reduce the impact of mistakes and compromise.

Related Topics

Continue with API concepts, configuration, environment variables, and backend proxy patterns.