> For the complete documentation index, see [llms.txt](https://docs.apismart.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apismart.ai/sdks-and-migration/javascript-and-typescript.md).

# JavaScript and TypeScript

Use JavaScript or TypeScript to send requests to the ApiSmart API with the built-in `fetch` API.

This guide shows a basic setup for Chat Completions, image generation, and video generation.

For general API rules, see [**API Basics**](/api-guides/api-basics.md).

***

### Before You Begin

Make sure you have:

* Node.js 18 or later
* An active **API Token**
* Sufficient **Current Balance**
* A valid **Model ID**

Set your API Token as an environment variable:

```bash
export APISMART_API_KEY="YOUR_API_KEY"
```

On PowerShell:

```powershell
$env:APISMART_API_KEY="YOUR_API_KEY"
```

> 🔐 Keep your API Token in a secure server-side environment. Do not expose it in browser-side code.

***

### Basic Setup

```javascript
const apiKey = process.env.APISMART_API_KEY;

if (!apiKey) {
  throw new Error("APISMART_API_KEY is not set.");
}

const headers = {
  Authorization: `Bearer ${apiKey}`,
  "Content-Type": "application/json",
};
```

The same authentication headers can be reused for supported ApiSmart endpoints.

***

### Chat Completions

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/chat/completions",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      messages: [
        {
          role: "user",
          content: "Hello!",
        },
      ],
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

console.log(result.choices[0].message.content);
```

Replace `YOUR_MODEL_ID` with the exact value shown in the selected model’s **Code Example**.

***

### Image Generation

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/images/generations",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      prompt: "A futuristic city at sunset",
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

console.log(result);
```

Image request and response fields may vary by model.

***

### Video Generation

Video generation uses an asynchronous task workflow.

For a video model that accepts `prompt` and `duration`:

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/video/tasks",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      prompt: "A cinematic view of waves at sunset",
      duration: 5,
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();
const taskId = result.id;

console.log(taskId);
```

Check the task status:

```javascript
const response = await fetch(
  `https://gw.apismart.ai/v1/video/tasks/${taskId}`,
  {
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

console.log(result);
```

> ⚠️ **Important:** Video models may use different fields such as `prompt`, `content`, `size`, or `resolution`. Always follow the selected model’s **Code Example**.

***

### TypeScript

The same request structure works in TypeScript.

For example:

```typescript
interface ChatResponse {
  choices: Array<{
    message: {
      role: string;
      content: string;
    };
  }>;
}

const result = (await response.json()) as ChatResponse;

console.log(result.choices[0].message.content);
```

Use model-specific types where the response structure differs.

***

### 🛠️ Common Problems

| Problem                   | What to Check                                     |
| ------------------------- | ------------------------------------------------- |
| **Authentication failed** | API Token and Bearer header                       |
| **Model not found**       | Exact Model ID and capitalization                 |
| **Invalid request**       | Endpoint, JSON body, and model-specific fields    |
| **Request failed**        | HTTP status and returned error message            |
| **Insufficient balance**  | Current Balance and API Token remaining allowance |

When troubleshooting, review the related request in [**Usage Logs and Costs**](/api-usage/usage-logs-and-costs.md).

> 🔐 Never include your full API Token in frontend code, logs, screenshots, or support messages.

***

### 🚀 Next Steps

Continue with:

* [**Python**](/sdks-and-migration/python.md)
* [**cURL**](/sdks-and-migration/curl.md)
* [**API Basics**](/api-guides/api-basics.md)
* [**Chat Completions API**](/api-guides/chat-completions-api.md)
* [**Image Generation API**](/api-guides/image-generation-api.md)
* [**Video Generation API**](/api-guides/video-generation-api.md)
