← Blog

How to Use an AI API: A Step-by-Step Guide

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

Using an AI API means sending a request over HTTPS to a model provider's endpoint with your text (or other input) and an API key, and getting back a generated response in JSON. In practice this involves four steps: get an API key, authenticate your requests, send a properly formatted message, and handle the response — either all at once or as a stream of tokens as they're generated.

If you've never called an AI API before, the good news is that the mechanics are the same as calling any REST API you've used before: an endpoint URL, a header carrying your credentials, a JSON body, and a JSON (or streamed) response. What trips people up isn't the HTTP part — it's understanding message formats, token limits, streaming, and tool use, which don't exist in typical CRUD APIs. This guide walks through each piece.

Step 1: Get an API key

Every AI API requires authentication. You'll typically get a key from the provider's dashboard after signing up, and it looks something like sk-... or sub_live_.... Treat it like a password:

If you already pay for a Claude subscription and want to expose it as a proper API with its own keys, usage tracking, and team seats, that's exactly what SubToAPI does — you get a sub_live_... key from your dashboard after signup instead of managing separate billing per provider.

export SUBTOAPI_KEY="sub_live_xxxxxxxxxxxx"

Step 2: Make your first request

Almost every AI API follows the same shape: a POST request to a /messages or /chat/completions-style endpoint with a model name, a list of messages, and a max token limit.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Explain what a race condition is in one paragraph."}
    ]
  }'

The response comes back as JSON with the generated text, a stop reason, and usage metadata (input/output token counts). That usage block matters — it's how you'll estimate and monitor cost per request. The quickstart and messages docs cover the exact request and response shape in more detail.

Same request in JavaScript

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-4",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "Explain what a race condition is in one paragraph." }
    ],
  }),
});

const data = await res.json();
console.log(data);

Step 3: Understand the message format

Most AI APIs use a conversation array rather than a single prompt string. Each entry has a role (user, assistant, sometimes system) and content. To carry context across turns, you resend the full history each time — the API itself is stateless:

messages: [
  { role: "user", content: "What's a hash map?" },
  { role: "assistant", content: "A hash map is a data structure..." },
  { role: "user", content: "How does it handle collisions?" }
]

This is the single most common source of confusion for developers new to AI APIs: there's no server-side session. If you want memory, you manage it in your own application, either by resending the full transcript or summarizing older turns to stay under the token limit.

Step 4: Handle streaming for long responses

For anything user-facing — chat UIs, live code generation — you don't want to wait for the entire response before showing anything. Streaming sends the response as a sequence of server-sent events, and you render tokens as they arrive.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "stream": true,
    "messages": [{"role": "user", "content": "Write a haiku about deploys."}]
  }'

Your client reads the event stream and appends each chunk to the UI as it's received. See streaming for a full worked example including error handling and reconnect logic.

Step 5: Give the model tools when it needs to act

Plain text generation covers a lot, but for tasks like "look up the weather" or "run this database query," you define tools — JSON schemas describing functions the model can call. The model doesn't execute anything itself; it returns a structured request for your code to run, and you send the result back in the next message.

tools: [
  {
    name: "get_stock_price",
    description: "Get the current price of a stock ticker",
    input_schema: {
      type: "object",
      properties: { ticker: { type: "string" } },
      required: ["ticker"],
    },
  },
]

This pattern — model requests a call, your app executes it, you feed the result back — is how most "AI agents" actually work under the hood. Details and a complete round-trip example are in tools.

Step 6: Watch tokens and costs

AI APIs bill by tokens (roughly 4 characters of English text), not requests. Every response includes usage counts for input and output tokens, so log them from day one. If you're running this across a team, a dashboard that aggregates usage per key or per seat saves you from digging through logs later — SubToAPI's pricing starts at €9/month for solo use and scales to per-seat plans for teams that need shared visibility into who's calling what.

Putting it together

A minimal, production-viable integration looks like: environment variable for the key, a thin wrapper function around the request, streaming for anything interactive, tool definitions for anything that needs to act on real data, and usage logging from the first request. Everything past that — retries, rate limit backoff, prompt caching — is optimization you add once the basic loop works.

questions

Do I need a different integration for every AI provider? No, if the API follows the common Messages-style format (roles, content, streaming, tools), your integration code is nearly identical across providers — you mainly change the endpoint and model name.

How do I keep conversation context across multiple calls? The API is stateless, so you resend the full message history (or a summarized version of it) with each request; there's no server-side session to rely on.

What's the cheapest way to start testing an AI API? Use a small max_tokens value and a cheap model tier while developing, watch the token usage in each response, and start on a plan with a free trial, like the one available at signup, before committing to production traffic.

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 →