← Blog

How to AI API: A Practical Setup Guide for Developers

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

How to AI API: The Short Answer

If you're asking "how to AI API," you're really asking three things: how do you get access to a model, how do you authenticate and send requests, and how do you turn the response into something your app can use. The core pattern is the same across nearly every provider: you get an API key, you send a JSON payload with your prompt or conversation history to an HTTPS endpoint, and you parse the JSON (or stream) that comes back.

This guide walks through that pattern step by step, using real request shapes, so you can go from zero to a working integration today — whether you're calling a model provider directly or routing through a service like SubToAPI that wraps an existing Claude subscription in a standard API.

Step 1: Get an API Key

Every AI API requires authentication, almost always via a bearer token in the request header. You typically get this key one of two ways:

The second path is useful if you already pay for a chat subscription and don't want a separate metered billing relationship. SubToAPI, for example, turns your existing Claude access into an application key (sub_live_...) you can drop into any codebase. You get the key immediately after signup, and there's a free trial before you commit to a plan.

Whichever path you take, treat the key like a password: never commit it to source control, and load it from an environment variable.

export SUBTOAPI_KEY="sub_live_xxxxxxxxxxxx"

Step 2: Send Your First Request

Almost all modern AI APIs use a "messages" format: an array of role/content objects representing the conversation so far. Here's what a basic request looks like with curl:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet",
    "max_tokens": 512,
    "messages": [
      {"role": "user", "content": "Explain what a REST API is in two sentences."}
    ]
  }'

The response comes back as JSON with the generated text, token usage, and a stop reason:

{
  "id": "msg_01AbC...",
  "role": "assistant",
  "content": [{ "type": "text", "text": "A REST API is..." }],
  "usage": { "input_tokens": 14, "output_tokens": 38 }
}

That usage block matters — it's how you track cost and volume per request, and it's what most dashboards (SubToAPI's included) use to build per-key and per-team usage reports. See the messages docs for the full request/response schema.

Step 3: Handle Multi-Turn Conversations

Real applications aren't single-shot. You maintain a conversation by appending each turn to the messages array and resending the whole history:

const messages = [
  { role: "user", content: "What's the capital of Peru?" }
];

async function ask(messages) {
  const res = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "claude-sonnet",
      max_tokens: 256,
      messages
    })
  });
  const data = await res.json();
  return data.content[0].text;
}

const reply = await ask(messages);
messages.push({ role: "assistant", content: reply });
messages.push({ role: "user", content: "What's its population?" });
const reply2 = await ask(messages);

Note that the API itself is stateless — your app owns the conversation history and resends it every time. This is the single biggest source of confusion for people building their first AI integration.

Step 4: Stream Responses for Better UX

Waiting for a full response before showing anything feels slow, especially for longer answers. Streaming sends tokens as they're generated so you can render text incrementally, the same way ChatGPT or Claude's own chat interface does. You enable it by setting "stream": true and reading the response as a stream of server-sent events instead of a single JSON blob. Full details, including how to parse the event chunks, are in the streaming docs.

Step 5: Add Tool Use When You Need It

Once your integration works for plain text, you'll often want the model to call functions in your own system — look up a record, run a calculation, hit an internal API. This is done via tool definitions: you describe available tools (name, description, input schema) in the request, and the model returns a structured tool call instead of plain text when it decides one is needed. Your code executes the tool and sends the result back as the next turn. The tools docs cover the schema and the full round-trip.

Choosing Between Direct Access and a Gateway

Calling a provider's API directly gives you the most control and the lowest possible latency overhead. Going through a gateway like SubToAPI makes sense when:

Plans start at €9/month for solo use, with team and scale tiers at €19 and €49 per seat — see pricing for the breakdown. The quickstart guide gets you from signup to your first successful request in a few minutes.

Common Mistakes to Avoid

Questions

Do I need to build my own backend to use an AI API? No — you can call the API directly from a server-side script, a serverless function, or a backend service. Avoid calling it from client-side JavaScript directly, since that would expose your API key.

What's the difference between an AI API and a chat app? A chat app is a finished product with a UI. An AI API is the raw interface that lets you build your own product, automation, or integration on top of the same underlying model.

Can I test an AI API without paying first? Most providers and gateways, including SubToAPI, offer a free trial or free tier so you can validate the integration before committing to a paid plan.

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 →