59API

← Voltar aos guias

Build a Low-Cost OpenAI-Compatible Chatbot Backend

API · EN · 2026-09-18

Build a production-ready chatbot backend with one API format

An OpenAI-compatible API lets your chatbot backend use the familiar chat completions request format while giving you flexibility over providers and models. This is useful when you want to switch between GPT models and Claude-family models without rewriting your application logic. In this hands-on example, you will build a small Node.js backend that accepts a user message, keeps a limited conversation history, and relays the request to an OpenAI-compatible endpoint.

59API is a practical option for this setup because its base URL is https://api.59api.com and it works with OpenAI SDKs, Codex, Claude Code, and standard OpenAI-compatible HTTP clients. It provides pay-as-you-go access to native official-quality Claude models, including Opus, Sonnet, Haiku, and Fable, as well as GPT models. That makes it especially useful for chatbot teams that need capable models without locking their code to a single provider.

1. Create the Node.js project and environment variables

Create a directory, initialize npm, and install Express and dotenv. Run: npm init -y && npm install express dotenv. Then create a file named .env with your credentials and the model identifier available in your 59API account:

PORT=3000
API_KEY=your_59api_key
MODEL=your_selected_model

Keep the API key on the server only. A browser application should call your backend endpoint, never the upstream AI endpoint directly. This prevents visitors from extracting your key and generating unexpected usage charges.

2. Add a chat endpoint

Create server.js. This example uses Node's built-in fetch, available in modern Node.js versions. It sends requests to the standard /v1/chat/completions path and returns only the generated assistant text to the frontend.

require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({ limit: '32kb' }));

const API_URL = 'https://api.59api.com/v1/chat/completions';
const historyBySession = new Map();

app.post('/api/chat', async (req, res) => {
  const { message, sessionId = 'anonymous' } = req.body;
  if (typeof message !== 'string' || !message.trim()) {
    return res.status(400).json({ error: 'message is required' });
  }
  if (message.length > 2000) {
    return res.status(400).json({ error: 'message is too long' });
  }

  const prior = historyBySession.get(sessionId) || [];
  const messages = [
    { role: 'system', content: 'You are a helpful support chatbot. Be concise and do not invent policies or prices.' },
    ...prior,
    { role: 'user', content: message.trim() }
  ];

  try {
    const upstream = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.API_KEY}`
      },
      body: JSON.stringify({ model: process.env.MODEL, messages, temperature: 0.4 })
    });

    const data = await upstream.json();
    if (!upstream.ok) return res.status(upstream.status).json(data);

    const reply = data.choices?.[0]?.message?.content || 'No reply returned.';
    historyBySession.set(sessionId, [...messages.slice(1), { role: 'assistant', content: reply }].slice(-12));
    res.json({ reply });
  } catch (error) {
    res.status(502).json({ error: 'AI provider request failed' });
  }
});

app.listen(process.env.PORT || 3000);

3. Test the backend locally

Start it with node server.js, then send a request using curl: curl -X POST http://localhost:3000/api/chat -H "Content-Type: application/json" -d '{"sessionId":"demo-1","message":"How do I reset my password?"}'. Your frontend can now POST the same JSON payload and display the reply field.

4. Make it safe and cost-aware

Because the request format remains OpenAI-compatible, changing models is generally a configuration change rather than a backend rewrite. 59API's low-cost, pay-as-you-go relay model can help keep experimentation affordable while preserving access to official-quality model options. If you are ready to test this architecture, sign up for 59API and create an API key for your first chatbot environment; its referral rebate can also reduce costs as your usage grows.

Preços · Docs

Pronto para começar?

Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.

Cadastro grátis