JavaScript and TypeScript
Learn how to call ApiSmart APIs with JavaScript and TypeScript, including model discovery, text streaming, image generation, file uploads, and asynchronous video tasks.
Use JavaScript or TypeScript to integrate ApiSmart into Node.js applications, backend services, serverless functions, and AI-powered products.
This guide uses the standard fetch API to demonstrate authentication, model discovery, text and image generation, streaming responses, file uploads, and asynchronous video tasks.
🚀 Before You Start
Make sure you have:
Node.js installed
An ApiSmart account
An active API Key
Sufficient wallet balance for paid requests
The examples below use modern Node.js with built-in fetch.
You do not need to install an additional HTTP client library.
🔑 Set Your API Key
Do not hard-code your API Key directly in your application source code.
Store it in an environment variable:
export APISMART_API_KEY="your-api-key"Then access it in JavaScript or TypeScript:
const API_KEY = process.env.APISMART_API_KEY;
if (!API_KEY) {
throw new Error("APISMART_API_KEY is not set");
}Set the ApiSmart Base URL:
For JSON requests, you can reuse these headers:
Keep your API Key private and never expose it in frontend browser code, public repositories, or client-side bundles.
🧩 Get Available Models
Retrieve the current model list with:
GET /v1/models
Use the returned:
as the model value in supported API requests.
Model IDs must match exactly, including periods (.), hyphens (-), and version numbers.
For model categories and current IDs, see Models and Model IDs.
💬 Chat Completions
Use:
POST /v1/chat/completions
Example:
The request uses the OpenAI-compatible messages format documented by ApiSmart.
For complete request behavior, see Chat Completions API.
🌊 Stream a Text Response
Set:
to enable streaming.
This example reads and prints data as it arrives.
ApiSmart currently documents enabling Chat streaming with "stream": true; the API specification does not define a separate JavaScript event parser or detailed chunk schema, so applications should process the returned stream according to their own requirements.
For an overview of streaming behavior, see Response Modes.
🖼️ Generate an Image
Use:
POST /v1/images/generations
Image generation is synchronous by default.
A single image typically takes approximately 20–40 seconds, while high-resolution, multi-reference, or sequential requests may take longer.
Your HTTP client should allow at least 90 seconds for image generation.
⏱️ Set an Image Request Timeout
You can use AbortSignal.timeout() in modern Node.js:
The example uses a 120-second timeout to provide additional time beyond the recommended minimum.
If a client disconnects early, generation may still complete and may still incur a charge.
🔄 Generate from a Reference Image
Provide a public image URL using image:
Multiple reference image URLs can also be supplied as an array where supported.
For image limits and supported parameters, see Image Generation API.
📤 Upload a Local Image
Local image uploads use:
POST /v1/images/edits
This endpoint uses multipart form data, not a JSON request body.
Example for modern Node.js:
Do not manually set:
for this request.
When using FormData, let the runtime generate the multipart Content-Type and boundary automatically.
🌊 Stream Image Generation
Supported image workflows can also use SSE streaming.
Set:
Example:
For sequential generation, SSE behavior, and supported image parameters, see Image Generation API and Response Modes.
🎬 Create a Video Task
Video generation is asynchronous.
Create a task with:
POST /v1/video/tasks
Save the returned task ID so you can query the generation status.
Video generation follows a create-task-and-query workflow rather than keeping the original request open until generation finishes.
For models where resolution and duration affect billing, explicitly provide those values instead of relying on defaults.
🔄 Query a Video Task
Use:
GET /v1/video/tasks/{id}
Possible task statuses include:
queued
Waiting in queue
running
Generation in progress
succeeded
Generation completed
failed
Generation failed
cancelled
Task was cancelled
expired
Task expired
These are the video task states defined by the current API.
⏳ Poll Until Video Generation Completes
A simple polling loop can look like:
This example checks the task every 5 seconds.
For HappyHorse, Seedance, multimodal inputs, and complete video parameters, see Video Generation API.
🕘 Retrieve Recent Generated Images
Use:
GET /v1/images
🕘 Retrieve Recent Generated Videos
Use:
GET /v1/videos
Image and video history can currently be queried for the most recent 7 days.
For history fields and storage information, see Generated Media History.
🟦 TypeScript Example
ApiSmart uses the same HTTP API from TypeScript. You can add your own interfaces to make application code easier to maintain.
For example:
These TypeScript interfaces are application-side examples rather than additional fields defined by the ApiSmart API.
You can expand them according to the response structures your application uses.
⚠️ Handle API Errors
Always check response.ok before processing the response:
Common API responses include:
400
invalid_request_error
Invalid request
401
invalid_api_key
Invalid API Key
402
insufficient_quota
Insufficient balance
403
model_not_allowed
Model unavailable to the API Key
429
rate_limit_error
Request rate limit exceeded
502 / 504
Gateway errors
Temporary upstream or network issue
503
Service unavailable
Provider or dependent service unavailable
The current API error definitions also include model-capability and resource-specific errors.
For complete details, see HTTP Status Codes and API Errors.
🔁 Retry Temporary Failures
Temporary 5xx responses may be retried with a delay.
Example:
Use retries for temporary service failures.
Do not repeatedly retry authentication errors or invalid request parameters without correcting the underlying problem.
✅ JavaScript and TypeScript Checklist
Before deploying your integration, verify that:
Your API Key is stored securely
API calls are made from trusted server-side environments
The Base URL is correct
Model IDs are copied exactly
JSON requests use
Content-Type: application/jsonMultipart uploads allow
FormDatato set the content typeImage requests allow sufficient processing time
Streaming responses are consumed incrementally
Video tasks are polled until they reach a final state
Temporary failures use an appropriate retry strategy
Your account has sufficient wallet balance
➡️ Next Steps
Continue with:
Models and Model IDs — Find valid model IDs
Chat Completions API — Build text generation workflows
Image Generation API — Generate and edit images
Video Generation API — Create and query video tasks
Response Modes — Understand standard, streaming, and asynchronous behavior
Generated Media History — Retrieve recent generated media
最後更新於
這有幫助嗎?