59API

← 返回教程列表

Build a Chatbot Backend with 59API and Node.js

API 使用 · EN · 2026-10-29

A small backend, without provider lock-in

A chatbot backend needs to accept conversation history, call a model, and return its answer without exposing your API key. This quick-start builds that path with Node.js, Express, and the OpenAI SDK.

59API is a low-cost, pay-as-you-go AI API relay supporting multiple model families through an OpenAI-compatible interface. That makes it useful for testing alternatives without rewriting your application. For example, you could evaluate DeepSeek V4 Flash and Gemini 2.5 Flash against the same chatbot prompts.

1. Create the project and configure access

Use Node.js 22 or newer. Create an empty directory, then install the dependencies:

npm init -y

npm install express openai

Create a .env file containing these three lines, replacing the placeholders with your credentials and the exact model identifier from your 59API dashboard:

API_KEY=your_59api_key

API_BASE_URL=https://api.59api.com

MODEL_ID=your_dashboard_model_id

The service base URL is https://api.59api.com. Verify the SDK base path in the current integration documentation: if the documented endpoint includes a version prefix such as /v1, include that prefix in API_BASE_URL. The SDK appends the chat-completions resource path. Do not assume a model’s display name is its API identifier.

Add .env to .gitignore. Your browser should call your backend, never the relay directly with your secret key.

2. Implement the chat endpoint

Save the following as server.mjs. It accepts only user and assistant messages, adds a server-controlled system instruction, and returns a simple JSON reply.

import express from 'express'; import OpenAI from 'openai'; const app = express(); app.use(express.json({ limit: '16kb' })); const client = new OpenAI({ apiKey: process.env.API_KEY, baseURL: process.env.API_BASE_URL, timeout: 30000, maxRetries: 1 }); app.post('/chat', async (req, res) => { const messages = req.body?.messages; if (!Array.isArray(messages) || messages.length === 0 || messages.length > 20 || messages.some(m => !['user', 'assistant'].includes(m?.role) || typeof m.content !== 'string' || m.content.length > 8000)) { return res.status(400).json({ error: 'Provide 1–20 user or assistant messages, each at most 8000 characters.' }); } try { const result = await client.chat.completions.create({ model: process.env.MODEL_ID, messages: [{ role: 'system', content: 'You are a helpful, concise assistant.' }, ...messages.map(m => ({ role: m.role, content: m.content }))] }); return res.json({ reply: result.choices[0]?.message?.content ?? '' }); } catch { return res.status(502).json({ error: 'The model request failed. Please try again.' }); } }); app.listen(3000, '127.0.0.1');

Start it with node --env-file=.env server.mjs. This example binds to localhost intentionally; do not expose an unauthenticated model proxy publicly.

3. Send a test conversation

From another terminal, run:

curl http://127.0.0.1:3000/chat -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"Explain HTTP caching in two sentences."}]}'

Expect a JSON object containing reply. For the next turn, send the earlier user message, the assistant reply, and the new user message. This example is stateless: it does not remember conversations unless your application supplies them.

If a request fails, check the configured base path, API key, account balance, and model identifier. Log upstream status codes server-side, but never return credentials or raw provider errors to clients.

4. Add production safeguards

5. Compare cost using real traffic

59API’s inexpensive pay-as-you-go access and native official-quality model offering make it a practical starting point without relying on downgraded substitutes. Still, benchmark answer quality, latency, and total token cost on your own tasks; OpenAI compatibility does not make every optional parameter interchangeable.

Track usage returned by the API where available, verify current pricing, and consider the referral rebate when estimating costs. When you are ready, sign up for 59API and test a small spending budget before scaling.

价格 · 接入文档

准备好开始了吗?

几分钟接入 Claude 与 GPT,全网超低价,原生不降智。立即注册即可领取 API 密钥。

免费注册