Claude API Chatbot Tutorial for Beginners
If you want to build a chatbot powered by Claude and you've never worked with the Claude API before, this tutorial walks you through everything you need: getting access, sending your first message, keeping conversation history, and handling streaming responses so your bot feels responsive instead of laggy.
By the end you'll have a working command-line chatbot in JavaScript that you can later wrap in a web UI, Slack bot, or support widget. No prior LLM experience required — just basic JavaScript and comfort running npm install.
What you actually need to build a Claude chatbot
A chatbot is three things glued together:
- An API endpoint that accepts a user message and conversation history, and returns Claude's reply.
- A loop that keeps track of the conversation so Claude remembers context.
- A front end (even a terminal) that displays messages and sends new ones.
That's it. There's no magic framework requirement — people overcomplicate step one the most, usually by skipping key management, rate limit handling, or billing setup entirely. We'll keep this simple and use SubToAPI, which turns your Claude access into a plain HTTPS API with an application key (sub_live_...), so you don't need to manage separate console billing or OAuth flows to get started. Sign up at /signup, grab your key, and you're ready.
Step 1: Get your API key
Create a free trial account and copy your key from the dashboard. Store it as an environment variable — never hardcode it in your source:
export SUBTOAPI_KEY="sub_live_xxxxxxxxxxxxxxxx"
If you're unfamiliar with how the request/response shape works, skim /docs/quickstart first — it covers the same request format shown below in more detail.
Step 2: Send your first message
Here's the minimal request to get a reply from Claude:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4",
"max_tokens": 300,
"messages": [
{ "role": "user", "content": "Say hi in one sentence." }
]
}'
You'll get back a JSON object with Claude's reply text plus usage metadata (input/output token counts). That metadata matters once you're running a real chatbot in production, because it tells you exactly what each conversation costs.
Step 3: Build the conversation loop
A chatbot isn't a single request — it's a growing array of messages. Claude doesn't retain memory between API calls, so you have to resend the whole conversation history each time. Here's a basic Node.js implementation:
import readline from "node:readline";
const apiKey = process.env.SUBTOAPI_KEY;
const history = [];
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
async function ask(userText) {
history.push({ role: "user", content: userText });
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 500,
messages: history,
}),
});
const data = await res.json();
const reply = data.content[0].text;
history.push({ role: "assistant", content: reply });
return reply;
}
function loop() {
rl.question("You: ", async (input) => {
const reply = await ask(input);
console.log("Claude:", reply);
loop();
});
}
loop();
Run this with node chatbot.js and you have a working terminal chatbot that remembers everything said in the session. Full request/response fields are documented at /docs/messages.
Step 4: Add a system prompt to shape behavior
Right now your bot has no personality or constraints. Add a system field to the request to define its role — for example, a support bot that only answers questions about your product:
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 500,
system: "You are a friendly support assistant for a bike rental app. Keep answers under 3 sentences. If you don't know something, say so.",
messages: history,
}),
Keep this short and specific. Vague system prompts produce vague bots.
Step 5: Stream responses so the bot feels fast
Waiting for a full response before showing anything makes a chatbot feel sluggish, especially for longer answers. Streaming sends tokens as they're generated, so you can print them as they arrive:
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 500,
stream: true,
messages: history,
}),
});
for await (const chunk of res.body) {
process.stdout.write(chunk.toString());
}
The streamed events follow a predictable format described in /docs/streaming — each event carries a text delta you append to the output as it arrives.
Step 6: Handle errors and rate limits gracefully
Beginners often skip this and get caught off guard the first time a request fails. At minimum, check the HTTP status and retry on 429s with backoff:
if (res.status === 429) {
await new Promise((r) => setTimeout(r, 2000));
return ask(userText); // retry
}
For anything beyond a toy project, also cap history length — long conversations cost more tokens per request since you resend everything each time. Trimming older turns or summarizing them keeps costs predictable.
Step 7: Give your bot tools (optional but powerful)
Once the basic loop works, you can let Claude call functions — look up order status, fetch weather, query a database — instead of just generating text. This is called tool use, and it's covered in depth at /docs/tools. It's the natural next step after you've got a plain chatbot running.
Where to go from here
You now have the full loop: send message, store history, stream reply, handle errors. From here you can:
- Swap the terminal for a web chat widget using the same fetch calls
- Add tool use for real actions, not just conversation
- Track token usage per user if you're billing customers
- Add team members to a shared dashboard for API key management and usage visibility — see /pricing for plan details if you're scaling past a solo project
How much does it cost to run a Claude API chatbot?
Cost depends on model choice and conversation length, since you resend history with every request. SubToAPI plans start at €9/month for a Solo plan, which is enough for most early-stage or personal chatbot projects — see /pricing for current tiers.
Do I need to use a framework like LangChain to build a Claude chatbot?
No. A chatbot is just a loop that sends an array of messages and appends the reply. Frameworks add convenience for complex agent behavior, but for a first chatbot, plain fetch calls are easier to debug and understand.
Why does my chatbot forget earlier messages?
Claude's API is stateless — it has no memory between calls. You must include the full conversation history in every request's messages array, or the model has no way of knowing what was said before.