← Blog

How to Use My API Key: A Quick Practical Guide

2026-09-17 · 5 min read · SubToAPI Team

If you've just been handed an API key and you're wondering what to actually do with it, the short answer is: you send it with every request, usually in an HTTP header, so the API can identify and authorize you. It is not a password you type into a login form — it's a credential your code attaches automatically to each call.

This article walks through exactly how that works in practice: where the key goes, how to test it before writing any code, what mistakes cause the most support tickets, and how to keep the key from leaking. The examples use curl and JavaScript, but the same pattern applies to almost every REST API you'll ever integrate with.

The basic pattern: authorization headers

Most modern APIs authenticate requests using the Authorization HTTP header, formatted as a Bearer token:

Authorization: Bearer YOUR_API_KEY

You add this header to every request you make to the API — not just the first one. There's no session or login step; the key itself proves who you are on each call.

Here's what that looks like with curl:

curl https://api.example.com/v1/resource \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"

And in JavaScript with fetch:

const response = await fetch("https://api.example.com/v1/resource", {
  method: "GET",
  headers: {
    "Authorization": `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json"
  }
});

const data = await response.json();

Some older or third-party APIs use a query parameter (?api_key=...) or a custom header (X-API-Key) instead of Authorization: Bearer. Always check the specific API's docs, but Bearer tokens are the most common convention in 2025 and the one you should default to unless told otherwise.

Step 1: Find where to put the key

Before writing code, confirm three things from the provider's documentation:

  1. Header name — usually Authorization, sometimes X-API-Key.
  2. Prefix — usually Bearer , sometimes none.
  3. Base URL — the API root you're sending requests to.

For SubToAPI, for example, the pattern is:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Say hello in one sentence."}]
  }'

The key format itself (sub_live_...) tells you which service issued it and often which environment (live vs. test). Getting the exact header and prefix right is the single most common source of "invalid API key" errors — not a broken key, but a malformed request.

Step 2: Test the key before writing real code

Don't debug your application and your API credentials at the same time. Test the key in isolation first, with a minimal curl command and no application logic involved:

curl -i https://api.example.com/v1/health \
  -H "Authorization: Bearer YOUR_API_KEY"

Check the HTTP status code:

Once a plain curl call succeeds, you know any errors afterward are in your code, not your credentials.

Step 3: Store the key as an environment variable

Never hardcode an API key directly in a source file. Use environment variables and load them at runtime:

# .env (not committed to git)
API_KEY=your_actual_key_here
import "dotenv/config";

const apiKey = process.env.API_KEY;

if (!apiKey) {
  throw new Error("Missing API_KEY environment variable");
}

Add .env to your .gitignore immediately — before you even paste the key in, if possible. A key committed to git history is compromised even if you delete it in a later commit, because it still exists in the repo's history.

Step 4: Handle errors and retries

A production integration should handle the predictable failure modes: expired or revoked keys, rate limits, and transient network errors.

async function callApi(payload) {
  const response = await fetch("https://api.example.com/v1/resource", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  });

  if (response.status === 401) {
    throw new Error("API key invalid or revoked — check your credentials");
  }

  if (response.status === 429) {
    const retryAfter = response.headers.get("Retry-After") || 1;
    await new Promise(r => setTimeout(r, retryAfter * 1000));
    return callApi(payload); // simple retry, add a max-attempts guard in production
  }

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}

This kind of wrapper saves you from silent failures where a 401 gets swallowed and your app just appears "broken" for no obvious reason.

Common mistakes that break API key usage

That last point is worth designing around from day one. If you're building on top of Claude and want per-application keys instead of one shared secret, SubToAPI issues individual sub_live_... keys per app or team member, with usage tracked per key — so you can see exactly which key is calling what, and revoke one without breaking everyone else. The quickstart covers generating your first key and making a request in under five minutes, and the Messages docs cover the request format in detail.

Keeping the key secure long-term

If you're evaluating providers, check whether the dashboard supports per-key usage metadata and revocation — the pricing page outlines which SubToAPI plans include team seats and multiple keys per account.

FAQ

Where exactly do I put my API key in a request? In almost all modern APIs, you add it to the Authorization HTTP header as Bearer YOUR_API_KEY. Check the provider's docs for the exact header name and prefix, since a few APIs use X-API-Key or a query parameter instead.

Why do I get a 401 error even though my key is correct? Usually it's a formatting issue: extra spaces, a missing Bearer prefix, wrong header name, or using a test key against a production endpoint. Test the key with a minimal curl command first to isolate the problem from your application code.

Is it safe to put my API key directly in my frontend JavaScript? No. Any key in client-side code is visible to anyone who opens browser dev tools. Keep API keys server-side, load them from environment variables, and have your frontend call your own backend, which then calls the third-party API with the key attached.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →