# Invoke server API

This document introduces the detailed steps to construct API requests and call the open platform server-side API through the NodeJS SDK.

## Step 1: Create and configure the API client

Before calling the API, you need to create an API Client that specifies information about the application, log levels, timeouts, and other basic information.

1. Create an API Client.

The creation method for enterprise self-built applications and store applications differs. The details are as follows:

- For enterprise self-built applications, use the following code to create an API Client.

```javascript
      import * as lark from '@larksuiteoapi/node-sdk';

const client = new lark.Client({
          appId: 'app id',
          appSecret: 'app secret'
      });
      ```

- For store applications, use the following code to create an API Client, indicating the current application as a store application by using `appType: lark.AppType.ISV`.

```javascript
      import * as lark from '@larksuiteoapi/node-sdk';

const client = new lark.Client({
          appId: 'app id',
          appSecret: 'app secret',
          appType: lark.AppType.ISV,
      });
      ```  
      **Note**: When making API calls using a store application, you must pass in the tenant Key (tenant_key) and the app_ticket (used to obtain the app_access_token for the store application). For detailed instructions, see the section **Necessary Operations for Store Applications to Call API** below.

2. (Optional) Customize API Client Configuration

When creating the API Client, it's possible to customize the configuration of the API Client. For example, set the log level, cache, etc. The table below explains the client constructor parameters.

Parameter | Type | Required | Description
---|---|---|---
appId | string | Yes | Application's App ID. How to obtain: Log in to the [Developer Console](https://open.feishu.cn/app), and get the application credentials (including App ID and App Secret) on the application details page under **Credentials and Basic Info**.
appSecret | string | Yes | The application's App Secret.
domain | Domain | string | No | Application domain. Commonly used to specify Feishu domain:<br>- Feishu: https://open.feishu.cn<br>- Lark: https://open.larksuite.com<br>If you need to configure other domains, you need to ensure that you pass the complete domain.<br>**Default value**: Domain.Feishu, which means using the Feishu domain by default. If it's Lark, it needs to be set to Domain.Lark.
httpInstance | HttpInstance | No | HTTP instance for SDK to send requests. By default, the SDK uses `axios.create()` to construct a defaultHttpInstance for HTTP calls.<br>You can import `defaultHttpInstance` from the SDK and add interceptors as needed. For example, the SDK filters the `data` field by default. If you need to get `logid` and other data, you can reset its interceptors. Example code:<br>```javascript <br>import { defaultHttpInstance } from '@larksuiteoapi/node-sdk';<br>defaultHttpInstance.interceptors.response.use((resp) => {<br>// You can handle some logic here<br>// Remember to return resp.data <br>return resp.data;<br>})<br>```<br>**Default value**: defaultHttpInstance
loggerLevel | LoggerLevel | No | Logging level. Enumeration values:<br>- error: Records error events that prevent part of the program from running.<br>- warn: Records some abnormal problems that may not affect continued program operation.<br>- info: Records key information during operation that needs to be monitored.<br>- debug: Records debugging information used to diagnose problems during debugging.<br>- trace: Records detailed information that can be used to track program operation during development or debugging.<br>**Default value**: info
logger | Logger | No | Logger, customizable as needed.
cache | Cache | No | Cache component for storing and retrieving cached data, such as tokens. If you don't specify a cache, the SDK initializes one. If you need to share data with an existing system, you can customize the cache by implementing the Cache interface. The default cache implementation: [default-cache.ts](https://github.com/larksuite/node-sdk/blob/main/utils/default-cache.ts)<br>```javascript<br>import get from 'lodash.get';<br>import { Cache } from '@node-sdk/typings';<br>export class DefaultCache implements Cache {<br>values: Map<<br>string | Symbol,<br>{<br>value: any;<br>expiredTime?: number;<br>} <br>>;<br>constructor() {<br>this.values = new Map();<br>}<br>// When there is a namespace, splice the namespace and key to form a new key<br>private getCacheKey(key: string | Symbol, namespace?: string) {<br>if (namespace) {<br>return `${namespace}/${key.toString()}`;<br>}<br>return key;<br>}<br>async get(key: string | Symbol, options?: {<br>namespace?: string<br>}) {<br>const cacheKey = this.getCacheKey(key, get(options, 'namespace'));<br>const data = this.values.get(cacheKey);<br>if (data) {<br>const { value, expiredTime } = data;<br>if (!expiredTime || expiredTime - new Date().getTime() > 0) {<br>return value;<br>}<br>}<br>return undefined;<br>}<br>async set(key: string | Symbol, value: string, expiredTime?: number, options?: {<br>namespace?: string<br>}) {<br>const cacheKey = this.getCacheKey(key, get(options, 'namespace'));<br>this.values.set(cacheKey, {<br>value,<br>expiredTime,<br>});<br>return true;<br>}<br>}<br>export const internalCache = new DefaultCache();<br>```
disableTokenCache | boolean | No | Whether to disable the token cache. If disabled (value true), tokens will not be cached and the system will automatically fetch a new token whenever required.<br>**Default value**: false, meaning it is not disabled
appType | AppType | No | Application type. By default, the absence of a value indicates a self-built application. If it's a store application, you must pass in AppType.ISV.<br>- AppType.ISV: Store application<br>- AppType.SelfBuild: Self-built application<br>**Default value**: AppType.SelfBuild
helpDeskId | string | No | Helpdesk ID. Required only when calling helpdesk APIs. It can be obtained from [Helpdesk Management Backend](https://feishu.cn/helpdesk/admin) under **Settings** > **API Credential**. For details, see [Helpdesk Access Guide](https://open.feishu.cn/document/ukTMukTMukTM/ugDOyYjL4gjM24CO4IjN).<br>**Note**: The Helpdesk ID and Token can only be viewed by the creator of the helpdesk.<br>![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/330d9fbaf98beb0d6e2a756350c7b8e2_3P9XpPS3l8.png?height=1560&lazyload=true&width=2884)
helpDeskToken | string | No | Helpdesk token. Required only when calling helpdesk APIs. It can be obtained from [Helpdesk Management Backend](https://feishu.cn/helpdesk/admin) under **Settings** > **API Credential**. For details, see [Helpdesk Access Guide](https://open.feishu.cn/document/ukTMukTMukTM/ugDOyYjL4gjM24CO4IjN).<br>**Note**: The Helpdesk ID and Token can only be viewed by the creator of the helpdesk.<br>![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/330d9fbaf98beb0d6e2a756350c7b8e2_3P9XpPS3l8.png?height=1560&lazyload=true&width=2884)

## Step 2: Constructing API requests

After creating an API Client within the project, you can start calling the Feishu open interface. You can use **client.domain.resource.methodName** to locate a specific API method, and then initiate a call to the particular API. It is recommended to quickly locate the API method through the [API Explorer](https://open.feishu.cn/api-explorer). For example, using the [Send message](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create) interface, you can either splice the API method through the address bar parameters or refer to the example code to locate the API method, as shown below.

- Method 1: Refer to the sample code of a specific API and directly obtain the method for constructing API requests from the code.
- Method 2: Obtain relevant parameters through the browser address bar of a specific API and splice the API method in the format of **client.domain.resource.methodName**.

- In the picture below, ① project represents **domain**
  - In the picture below, ② resource represents **resource**
  - In the picture below, ③ apiName represents **methodName**

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/5d2c6883596d2a44bb83dfbe7d57e06d_BTx30AaY7C.png?height=1684&lazyload=true&maxWidth=600&width=2882)

From version 1.22 of the NodeJS SDK, multi-version invocation is supported. If an API under a specific domain (project) cannot be found in the SDK, you can get it through project.version. For example, as shown below, tasks (task) contain both v1 and v2 versions.

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/71e4da95e5023fe51acb57f27d376865_9rk45yH2y4.png?height=410&lazyload=true&maxWidth=500&width=860)

Selecting v2 will add some methods.

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/7fc8aaab7e6c55e6e5b4258a67acafc0_8JQL1ucgKm.png?height=576&lazyload=true&maxWidth=500&width=1608)

An example of calling is as follows, where the send message interface is called through the client.

```javascript
import * as lark from '@larksuiteoapi/node-sdk';

// Build API Client
const client = new lark.Client({
    appId: 'app id',
    appSecret: 'app secret'
});

// Call the "Send Message" interface through Client
const res = await client.im.message.create({
    params: {
        receive_id_type: 'chat_id',
    },
    data: {
        receive_id: 'receive_id',
        content: JSON.stringify({text: 'hello world'}),
        msg_type: 'text',
  },
});
```

The SDK includes a link to the Feishu Open Platform [API Explorer](https://open.feishu.cn/api-explorer). In the development tool, you can click **click to debug** in the method comments of the specific API to jump to the API Debugging Console for debugging.

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/3860ebdf6797d3e75b161bf1409281cd_ent8KutOhk.png?height=234&lazyload=true&maxWidth=500&width=1082)

### Necessary Operations for Store Apps Calling API

When using a store app to call the API, `appType: lark.AppType.ISV` must be declared in the client, and the SDK will execute different logic branches based on this declaration. The logic branch for store apps is different from enterprise self-built apps. Store apps must pass in tenant_key and app_ticket in the code.  
Why store apps need tenant_key and app_ticket when calling API:

- [tenant_key](https://open.feishu.cn/document/ukTMukTMukTM/uYTM5UjL2ETO14iNxkTN/terminology#495685b5): A store app will be installed in multiple tenants; the tenant_key is the unique identifier of the tenant, used to distinguish different tenants.
- [app_ticket](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/application-v6/event/app_ticket-events): To improve data access security, Feishu adds `app_ticket` as a security credential for store apps, used to obtain app_access_token of store apps. `app_ticket` is automatically pushed every hour to the event subscription request address configured by the store app.

When obtaining the authorized access credential `tenant_access_token` of an enterprise, these two values are needed, but they cannot be actively obtained through the SDK and must be passed in externally. Therefore, for store apps, the SDK provides a way to pass in these two values.

1. Subscribe to the `app_ticket` event within the application.

Refer to the [app_ticket event](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/application-v6/event/app_ticket-events) for specific instructions on how to subscribe to the event.

2. After constructing the API Client for the store application in your project, use `EventDispatcher` to receive and process the app_ticket event.

Using Node's default HTTP service as an example, the sample code is as follows:

```javascript
    import * as http from "http";
    import * as lark from '@larksuiteoapi/node-sdk';

const ISVEventDispatcher = new lark.EventDispatcher();

const server = http.createServer();
    // /webhook/event is the Path configured for the event receiving address on the open platform
    server.on('request', lark.adaptDefault('/webhook/event', ISVEventDispatcher));
    server.listen(3000);
    ```

The `EventDispatcher` will internally receive the `app_ticket` event by default and write the obtained `app_ticket` to the cache.

3. Use the client to call the interface and explicitly pass the `tenant_key` value using the `withTenantKey` method.

The client will combine the `app_ticket` written in the cache from the previous step to obtain the `tenant_access_token` (and cache it), then make the interface call request.

```javascript
    import * as fs from "fs";
    import * as lark from '@larksuiteoapi/node-sdk';

const res = await SDKClient.im.file.create({
        data: {
            file_type: "mp4",
            file_name: "测试.mp4",
            file: fs.readFileSync("file path"),
        }
    }, lark.withTenantKey('tenant key'));

console.log(res);
    ```

## Step 3 (Optional): Set request options

When making an API call, you can set relevant request-level parameters, such as passing a `userAccessToken` (user access token) or custom headers.

- Sample code for custom headers is shown below.

```javascript
await client.im.message.create({
    params: {
        receive_id_type: 'chat_id',
    },
    data: {
        receive_id: 'receive_id',
        content: JSON.stringify({text: 'hello world'}),
        msg_type: 'text',
    },
}, {
    headers: {
        customizedHeaderKey: 'customizedHeaderValue'
    }
});
```

- The SDK encapsulates common modification operations into methods. The available methods are as follows:

Method | Description
---|---
withTenantKey | Set the tenant key (`tenant_key`). This value must be passed when calling the API with a store application. For details on how to obtain it, see [tenant_key](https://open.feishu.cn/document/ukTMukTMukTM/uYTM5UjL2ETO14iNxkTN/terminology#495685b5).
withTenantToken | Set the application identity token (`tenant_access_token`). How to obtain it:<br>- [Get tenant_access_token for store application](https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token)<br>- [Get tenant_access_token for self-built application](https://open.feishu.cn/document/ukTMukTMukTM/ukDNz4SO0MjL5QzM/auth-v3/auth/tenant_access_token_internal)
withUserAccessToken | Set the user identity token (`user_access_token`). How to obtain it: [Get user_access_token](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/authentication-management/access-token/get-user-access-token)
withHelpDeskCredential | Whether to include the Helpdesk token in the request. It is required only when calling the API for Helpdesk services. The token can be obtained in the **Settings** > **API Credential** section of the [Helpdesk Admin Console](https://feishu.cn/helpdesk/admin). For more details, refer to the [Helpdesk Integration Guide](https://open.feishu.cn/document/ukTMukTMukTM/ugDOyYjL4gjM24CO4IjN).<br>**Note**: The Helpdesk token can only be viewed by the Helpdesk creator.<br>![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/330d9fbaf98beb0d6e2a756350c7b8e2_3P9XpPS3l8.png?height=1560&lazyload=true&maxWidth=400&width=2884)
withAll | To merge the results of the aforementioned methods.

The configuration examples of the above methods in the code are as follows. For more code examples, refer to [request-with.ts](https://github.com/larksuite/node-sdk/blob/main/client/request-with.ts).

```javascript
// Example of using a single method
await client.im.message.create({
    params: {
        receive_id_type: 'chat_id',
    },
    data: {
        receive_id: 'receive_id',
        content: JSON.stringify({text: 'hello world'}),
        msg_type: 'text',
    },
}, lark.withTenantToken('tenant token'));

// Example of using multiple methods, using withAll to combine methods
await client.im.message.create({
    params: {
        receive_id_type: 'chat_id',
    },
    data: {
        receive_id: 'receive_id',
        content: JSON.stringify({text: 'hello world'}),
        msg_type: 'text',
    },
}, lark.withAll([
    lark.withTenantToken('tenant token'),
    lark.withTenantKey('tenant key')
]));
```

## Step 4: Run the project

After completing the above steps, you can run the project to call the API. You can run the project using development tools, or you can run it from the command line according to the project's deployment situation using the `node {project_file.js}` command, as shown below.

- Successful execution will return the interface response parameters:

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/98e93241e89f978971e5be1168bb6a9c_CfRluI0hXM.png?height=880&lazyload=true&maxWidth=500&width=1080)

- Unsuccessful execution will return the corresponding error code and error message:

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/de226cbbcb3e54ff8e9d0c26645421ce_8uIIDtP7qL.png?height=840&lazyload=true&maxWidth=500&width=2220)

## Introduction to API calling methods

The NodeJS SDK, in order to improve the efficiency of API calls, has encapsulated some API calling methods, including paginated queries, file uploads, file downloads, etc.

### Paginated queries

For APIs that return values in a paginated form, the SDK offers an iterator-based encapsulation (methods with the suffix WithIterator), eliminating the need for repeatedly obtaining data based on page_token, thereby enhancing ease of use. For example, using the [Get department direct users list](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/user/find_by_department) API, the paginated query can be done as follows:

```javascript
// Process 20 data items each time
for await (const items of await client.contact.user.findByDepartment({
    params: {
        department_id: '0',
        page_size: 20,
    },
})) {
    console.log(items);
}

// You can also use next to manually control the iteration, fetching 20 data items each time
const listIterator = await SDKClient.contact.user.findByDepartment({
    params: {
        department_id: '0',
        page_size: 20,
    },
});
const { value } = await listIterator[Symbol.asyncIterator]().next();
console.log(value);
```

You can also use the version without iterator encapsulation, where you need to manually perform paginated calls based on the returned page_token each time.

### File upload

The SDK encapsulates the file upload processing logic. It works the same way as normal API calls. For example, using the [Upload file](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/file/create) API, you can pass parameters to call it.

```javascript
const res = await client.im.file.create({
    data: {
        file_type: 'mp4',
        file_name: 'test.mp4',
        file: fs.readFileSync('file path'),
    },
});
```

If the above method throws error 1061002 in actual application, you can try changing the file type to stream. The code example is as follows:

```javascript
let Duplex = require('stream').Duplex;

function bufferToStream(buffer) {  
  let stream = new Duplex();
  stream.push(buffer);
  stream.push(null);
  return stream;
}
```

### File download

The SDK encapsulates the returned binary stream, eliminating the handling of the stream itself. When calling the [Download file](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/file/get) API, you just need to call the writeFile method to write the data to a file.

```javascript
const resp = await client.im.file.get({
    path: {
        file_key: 'file key',
    },
});
await resp.writeFile(`filepath.suffix`);
```

If you want to customize the handling of the stream, you can call the getReadableStream method to get the stream. The example below writes the stream to a file.

```javascript
import * as fs from 'fs';

const resp = await client.im.file.get({
    path: {
        file_key: 'file key',
    },
});
const readableStream = resp.getReadableStream();
const writableStream = fs.createWriteStream('file url');
readableStream.pipe(writableStream);
```
**Note**: The stream can only be consumed once. If you used writeFile to consume the stream, the getReadableStream call will either throw an error or return an empty stream. If you need to consume the stream multiple times, you can use getReadableStream to get the stream, then read the data from the stream to cache it, and let the consumers use the cached data.

### Feishu card

The open platform provides the [card template](https://open.feishu.cn/document/uAjLw4CM/ukzMukzMukzM/feishu-cards/send-feishu-card#718fe26b) capability. When [sending a card message](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create), you only need to provide the template ID and content. The SDK encapsulates the card template call, adding ByCard call methods in the interface supporting message cards. You simply need to pass `template_id` and `template_variable`.

```javascript
client.im.message.createByCard({
  params: {
    receive_id_type: 'chat_id',
  },
  data: {
    receive_id: 'your receive_id',
    template_id: 'your template_id',
    template_variable: {
      content: "Card Content",
      title: "Card Title"
    }
  }
});
```

If you need to send a message based on a card's JSON data, use the [send message](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create) interface to send a simple card with `title` and `content`. Example code is as follows:

```javascript
client.im.message.create({
  params: {
    receive_id_type: 'chat_id',
  },
  data: {
    receive_id: 'your receive_id',
    content: JSON.stringify({
        "config": {
          "wide_screen_mode": true
        },
        "elements": [
          {
            "tag": "markdown",
            "content": "Card Content"
          }
        ],
        "header": {
          "template": "blue",
          "title": {
            "content": "Card Title",
            "tag": "plain_text"
          }
        }
      }
    ),
    msg_type: 'interactive'
  }
})
```

Example effect:

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/9d27fcddc76396b4ab5b20b43f97c8d8_lOuLAagpBA.png?height=210&lazyload=true&maxWidth=500&width=1224)

The SDK has a built-in basic message card for you to experience.

```javascript
import * as lark from '@larksuiteoapi/node-sdk';
client.im.message.create({
  params: {
    receive_id_type: 'chat_id',
  },
  data: {
    receive_id: 'your receive_id',
    content: lark.messageCard.defaultCard({
      title: 'Card Title',
      content: 'Card Content'
    }),
    msg_type: 'interactive'
  }
})
```

Example effect:

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/9d27fcddc76396b4ab5b20b43f97c8d8_seTUt6LN9m.png?height=210&lazyload=true&maxWidth=500&width=1224)

## FAQ

### How to quickly get the sample code corresponding to the interface?

The Feishu open platform provides an [API Explorer](https://open.feishu.cn/api-explorer) through which you can quickly debug server APIs, quickly obtain resource IDs, and generate sample code in multiple languages, saving you development costs. For example, using the API debugging console to call the [send message](https://open.feishu.cn/api-explorer/cli_a61e4f821889d00c?apiName=create&from=op_doc_tab&project=im&resource=message&version=v1) interface, after successfully completing the test in the console, you can check the sample code for the related Node SDK interface on the **Sample Code** page.

![](//sf3-cn.feishucdn.com/obj/open-platform-opendoc/f5fa6a3997543573c3fe8bbdd6a92268_n9CLFtpcAT.png?height=1392&lazyload=true&maxWidth=600&width=2882)

### How to call the previous API version, APIs not searchable in the API debugging console, or APIs not found in the SDK?

You can use the native mode provided by the SDK to call the API (which requires using the request method on the Client).

```javascript
import * as lark from '@larksuiteoapi/node-sdk';

const client = new lark.Client({
    appId: 'app id',
    appSecret: 'app secret'
});

const res = await client.request({
    method: 'POST',
    url: 'xxx',
    data: {},
    params: {},
});
```

The parameter descriptions below can be obtained through specific API documentation. For example: [send message](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create)

- method: Specifies the HTTP method required by the API.
- url: Specifies the HTTP URL of the API, including any path parameters.
- data: Interface request body.
- params: Interface query parameters.

### When customizing domain in Client, does the URL need a slash '/' at the end?

No. For example: `domain: https://www.example.com` does not need a trailing `/`.

### How to Pass Values When Query Parameters are Lists in API Calls?

- Method 1: Upgrade the NodeJS SDK to version 1.37.2 to resolve the issue.
- Method 2: Use `paramsSerializer` and serialize the parameters with [https://www.npmjs.com/package/qs](https://www.npmjs.com/package/qs).

```js
    axios.get('/myController/myAction', {
      params: {
        storeIds: [1, 2, 3]
      },
      paramsSerializer: params => {
        return qs.stringify(params)
      }
    })
    ```

### Automatic Token Acquisition, Caching, and Refreshing

The SDK automatically manages the acquisition, caching, and refreshing of the `tenant_access_token` by default. When initializing the `Client`, you only need to provide the `appId` and `appSecret`. The SDK will automatically request a Token before the first API call and cache it.
To prevent the Token from expiring exactly during transmission due to network latency or other factors, the SDK invalidates the token **3 minutes early** based on its `expire` time and re-acquires it during the next request, effectively avoiding the risk of expiration at critical moments.

```javascript
import { Client } from '@larksuiteoapi/node-sdk';
// Only App ID and App Secret are required
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
});
// Call APIs directly, the SDK handles the Token automatically
async function main() {
    const response = await client.im.message.create({
        /* ...params */
    });
    console.log(response);
}
```

**Practical Advice**:
- Unless you have specific requirements (such as implementing a centralized Token management service), it is **strongly recommended** to keep the default behavior, as this is the most efficient and simplest way to use the SDK.
- The example code in the Feishu Open Platform API Explorer may show the usage of `lark.withTenantToken("token")` for debugging convenience. This method is suitable for temporary testing but is **not recommended** for production environments because Tokens expire, and hardcoding or manual passing can lead to service interruptions.

### Disabling Cache and Manually Passing Tokens

In certain scenarios (e.g., using external caches in stateless environments like Serverless), you may want to disable the SDK's built-in cache. After setting `disableTokenCache` to `true`, every API request **must** manually pass a valid Token via `lark.withTenantToken()` or `lark.withUserAccessToken()`.

```javascript
import { Client, withTenantToken } from '@larksuiteoapi/node-sdk';
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
    disableTokenCache: true, // Disable built-in Token cache
});
async function sendMessageWithManualToken(token: string) {
    const res = await client.im.chat.list(
        {},
        withTenantToken(token) // Must manually pass Token for every call
    );
    console.log(res);
}
```
**Note**: If cache is disabled but no Token is passed manually, you will receive a `Missing access token for authorization` error (error code `99991661`).

### Using `withUserAccessToken` to Act on Behalf of a User

When you need to perform operations on behalf of a specific user (e.g., operating on files in that user's drive), you should use `withUserAccessToken` to pass that user's `user_access_token`.

```javascript
import { Client, withUserAccessToken } from '@larksuiteoapi/node-sdk';
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
});
// Access user's drive files using User Access Token
async function listUserDriveFiles(userToken: string) {
    const res = await client.drive.file.list(
        {}, 
        withUserAccessToken(userToken) // Pass user's Access Token
    );
    console.log(res.data.files);
}
```

### Custom Cache Implementation

If you wish to store Tokens in Redis or other external storage, you can implement a custom cache. Simply create an object that conforms to the `ICache` interface (methods: `get`, `set`, `has`) and pass it when initializing the client.

```javascript
import { Client, ICache } from '@larksuiteoapi/node-sdk';
// Example: Simple cache implemented with Map, replace with Redis in actual scenarios
class RedisCache implements ICache {
    // private redisClient; // Assume this is your Redis client instance
    async set(key: string, value: any, expired?: number): Promise<void> {
        // In actual scenarios, use the expired parameter for Redis TTL
        // await this.redisClient.set(key, JSON.stringify(value), { EX: expired });
        console.log(`Setting cache for key: ${key}`);
    }
    async get(key: string): Promise<any> {
        // const value = await this.redisClient.get(key);
        // return value ? JSON.parse(value) : null;
        console.log(`Getting cache for key: ${key}`);
        return null;
    }
    async has(key: string): Promise<boolean> {
        // const exists = await this.redisClient.exists(key);
        // return exists === 1;
        console.log(`Checking cache for key: ${key}`);
        return false;
    }
}
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
    cache: new RedisCache(),
});
```
**Cache Isolation for Multi-instance Clients**
Starting from SDK `v1.10.0`, the default memory cache supports **Namespace Isolation based on App ID**. This means each `Client` instance automatically possesses an independent cache space, allowing you to safely use multiple `Client` instances in the same process without extra configuration.
If you use a custom cache (as in the example above), please ensure your cache `key` design includes `appId` as an isolation dimension to prevent Token confusion between different apps. The `key` passed by the SDK to `cache.set` already contains the `appId` by default, so you can use it directly.

### Getting Complete Response Information (e.g., Log ID)

By default, SDK API calls only return the `data` part of the response body. If you need complete response information, such as `headers` (which includes `X-Tt-Logid` for troubleshooting), you can achieve this by modifying `axios` interceptors.

**Difference Explanation: Custom Interceptors vs. Response Structure Risks**
The SDK allows adding interceptors by modifying `defaultHttpInstance` or passing a custom `httpInstance`, but these two methods carry different levels of risk when modifying response structures.

- **Method 1 (Low Risk): Modifying Default Instance to Get Extra Info**
  If you only want to obtain extra info like `logid` and then continue returning `resp.data`, you can directly modify `defaultHttpInstance`. This is low risk because the SDK's Token management logic still receives the expected `data` structure.
- **Method 2 (High Risk): Passing Custom Instance and Changing Response Structure**
  If you pass a brand new `httpInstance` during `Client` initialization and completely change the return structure in its response interceptor (e.g., returning `resp` instead of `resp.data`), this will **break the SDK's built-in Token management mechanism**, causing Token acquisition and refresh failures.

**Conclusion**: Unless you fully understand the internal mechanisms of the SDK and intend to manage Tokens yourself, **do not** change the final data structure returned to the SDK in the response interceptor of a custom `httpInstance`.

**Example: Getting Log ID Without Breaking Original Flow**
```javascript
import { defaultHttpInstance } from '@larksuiteoapi/node-sdk';
// Clear default response interceptors
defaultHttpInstance.interceptors.response.handlers = [];
// Add a new interceptor to return the complete response object temporarily or log headers
defaultHttpInstance.interceptors.response.use((resp) => {
    // resp object contains complete info like headers, status, data, etc.
    console.log('Log ID:', resp.headers['x-tt-logid']);

// You can do custom processing here, but you MUST return data to ensure SDK works properly
    return resp.data;
});
// All subsequent API requests will pass through this new interceptor
```

### Batch Adding Custom Request Headers

If you need to uniformly add custom Headers to all outgoing API requests (e.g., for gateway verification, link tracing), you can use a `request` interceptor.

```javascript
import { defaultHttpInstance } from '@larksuiteoapi/node-sdk';
defaultHttpInstance.interceptors.request.use(
  (req) => {
    if (req.headers) {
      req.headers['X-Custom-Header'] = 'Your-Value';
    }
    return req;
  }
);
```

### How to Locate Semantic Methods?

One of the core advantages of the SDK is providing semantic calling methods consistent with the Feishu Open Platform https://open.feishu.cn/api-explorer. You can piece together the corresponding method name based on the API documentation or the URL path in the debug console, following the structure `client.{project}.{resource}.{method}`.

**Example**: API for getting user info `https://open.feishu.cn/open-apis/contact/v3/users/:user_id`:
- `project`: `contact`
- `version`: `v3`
- `resource`: `user`
- `method`: `get` (HTTP method)
The corresponding SDK call is `client.contact.v3.user.get()`.

**Practical Advice**:
- **Fastest Way**: In the code example section of the API Explorer page, you can directly find the corresponding Node.js SDK usage.
- **Version Note**: If an API cannot be found under `client.{project}`, try adding the version number, like `client.{project}.{version}`.

### API Multi-version Support

Starting from `v1.22.0`, the SDK supports multi-version API calls. When an API has multiple versions (e.g., `v1`, `v2`), it is recommended to **explicitly specify the version number** to use the latest features and definitions.

```javascript
// Call v1 version of create task interface
await client.task.v1.task.create({ /* ... */ });
// Call v2 version of create task interface
await client.task.v2.task.create({ /* ... */ });
```
**Note**: To maintain backward compatibility, call methods without version numbers (like `client.task.comment.create`) will continue to point to the historical version fixed at the time of the `v1.22.0` release.

### How to Handle Array-type Query Parameters?

For some GET requests, the query parameter (Query Parameter) may be an array, for example, passing multiple `user_id`s when batch fetching user info.

**Solutions**:
- **Option 1 (Recommended)**: **Upgrade SDK to `1.37.2` or higher**. Starting from this version, the SDK internally handles the serialization of array parameters automatically, so you can pass arrays directly in `params`.
- **Option 2 (Legacy SDK)**: If you cannot upgrade temporarily, you can manually call the `client.request` method and provide a custom `paramsSerializer` function to "flatten" the array parameters.

```javascript
import qs from 'qs';
// Only applicable for legacy handling where SDK cannot be upgraded
await client.request({
  url: '/open-apis/contact/v3/users/batch',
  method: 'GET',
  params: {
    user_ids: ['ou_xxx', 'ou_yyy'], // Pass array directly
  },
  // Use qs library to serialize parameters
  paramsSerializer: params => {
    return qs.stringify(params, { arrayFormat: 'repeat' });
  },
});
```

### How to Call APIs Not Covered by SDK?
Although the SDK aims to cover all Feishu Open Platform APIs, due to documentation structure, release cycles, or gray-scale testing, a small number of APIs may not be included.
In this case, you can use the generic `client.request` method to initiate calls, which provides configuration options similar to `axios`.

```javascript
const response = await client.request({
  method: 'POST',
  url: '/open-apis/some/unsupported/api/v1',
  data: {
    // request body
  },
  params: {
    // query params
  }
});
```

### Using in Non-Node.js Environments like Cloudflare Workers

Modern Serverless environments like Cloudflare Workers and Deno are based on the Fetch API, which differs from standard Node.js environments. The default `adapter` of `axios` (the underlying dependency of the SDK) does not work in these environments, leading to `adapter is not a function` errors.

**Solution**: You need to manually replace the `axios` instance with an adapter compatible with the Fetch API, such as `@haverstack/axios-fetch-adapter`.

**Difference Explanation: Two Adaptation Methods**
There are two ways to adapt to Cloudflare Workers with the same effect. You can choose based on your code style and whether you need more custom `axios` features.

- **Method 1 (Recommended): Pass Custom `httpInstance`**
  This method is more flexible, allowing you to configure more options (like timeout, interceptors) when creating the `axios` instance.
- **Method 2: Directly Modify Default Instance's `adapter`**
  This method is more direct. If you only need to change the `adapter` without other changes, the code is more concise.

**Method 1: Pass Custom `httpInstance` (Recommended)**
```javascript
import { Client } from '@larksuiteoapi/node-sdk';
import axios from 'axios';
import fetchAdapter from '@haverstack/axios-fetch-adapter';
// 1. Create an axios instance configured with fetch adapter
const customHttpInstance = axios.create({
    adapter: fetchAdapter,
    // You can add other axios configurations here
});
// 2. Pass this instance when initializing Client
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
    httpInstance: customHttpInstance,
});
// Now client can initiate requests normally in Cloudflare Workers environment
```

**Method 2: Directly Modify Default Instance's `adapter`**
```javascript
import { Client } from '@larksuiteoapi/node-sdk';
import fetchAdapter from '@haverstack/axios-fetch-adapter';
const client = new Client({
  appId: 'YOUR_APP_ID',
  appSecret: 'YOUR_APP_SECRET',
});
// Directly change the adapter of the default HTTP instance
client.httpInstance.defaults.adapter = fetchAdapter;
// Now client can also initiate requests normally
```

### Current Status of Deno Support

Currently, the SDK is primarily designed for Node.js environments and does not officially support Deno. The main obstacles are the packaging of underlying dependencies (like `axios`) and environment compatibility issues. There is a temporary community solution using `import_map` to force specific `axios` compatible versions, but this is not officially supported and may break with dependency updates.
If you need to call Feishu APIs in a Deno environment, the safer choice at this stage is to use Deno's built-in `fetch` API directly.

### Pagination and Iterators
The SDK provides convenient iterator wrappers for many `list` interfaces that support pagination (e.g., `client.im.chat.listWithIterator()`), which can automatically handle pagination logic.
However, not all pagination interfaces support this feature. If a `list` interface does not provide a corresponding `...WithIterator` method, this is usually because its API definition does not meet the specifications for automatically generating iterators. In this case, you need to perform manual pagination polling:

```javascript
async function listAllItemsManually(client) {
  let allItems = [];
  let pageToken: string | undefined = undefined;
  let hasMore = true;
  while (hasMore) {
    const res = await client.im.chat.list({ // Assume this interface has no iterator
      params: {
        page_size: 100,
        page_token: pageToken,
      },
    });
    if (res.data.items) {
      allItems = allItems.concat(res.data.items);
    }

hasMore = res.data.has_more;
    pageToken = res.data.page_token;
  }
  return allItems;
}
```
**When to use Manual Pagination vs. Semantic Methods?**
- **Prioritize Iterators**: If the `client.{...}.listWithIterator` method exists, always prioritize using it as the code is cleaner and less error-prone.
- **Fallback to Manual Polling**: Adopt the manual pagination polling pattern above only when the iterator method is missing.

### Registering and Handling Events
`EventDispatcher` is the core for handling all event subscriptions. You can use the `register` method to register asynchronous handler functions for different types of events and call the `invoke` method in your Web framework to dispatch them.

```javascript
import { Client, EventDispatcher } from '@larksuiteoapi/node-sdk';
import express from 'express';
// 1. Initialize Client and EventDispatcher
const client = new Client({ /* ... */ });
const eventDispatcher = new EventDispatcher({
    verificationToken: 'YOUR_VERIFICATION_TOKEN',
    encryptKey: 'YOUR_ENCRYPT_KEY', // If encryption is enabled
}).register({
    // 2. Register message receive event handler
    'im.message.receive_v1': async (event) => {
        console.log('Received message event:', event);
        const { message } = event;
        // Process your business logic here, e.g., reply to message
        if (message.message_type === 'text') {
            await client.im.message.reply({
                path: { message_id: message.message_id },
                data: {
                    content: JSON.stringify({ text: 'Message received!' }),
                    msg_type: 'text',
                },
            });
        }
        return { success: true };
    },
    'contact.user.created_v3': async (data) => {
        console.log('New user created:', data);
    }
});
// 3. Call in your Web framework
const app = express();
app.use(express.json());
app.post('/webhook/event', (req, res) => {
    const data = { headers: req.headers, body: req.body };

// Suggestion: Respond 200 first, then process asynchronously to avoid timeout retries
    res.status(200).send('OK');
    eventDispatcher.invoke(data).catch(err => {
        console.error('Event processing error:', err);
    });
});
app.listen(3000, () => console.log('Server is running on port 3000'));
```

### URL Verification Challenge

When you configure the Request URL for event subscriptions in the Open Platform, Feishu will send a `challenge` request of type `url_verification` to that URL. The SDK's built-in `EventDispatcher` or framework adapters (like Express, Koa) **handle this process automatically**; you do not need to write any special code. As long as your service can correctly receive the request and pass it to the SDK, the verification will pass automatically.

### Avoiding Duplicate Event Pushes and Event Deduplication

Feishu's event push mechanism requires your service to return an HTTP 200 status code within **3 seconds** of receiving an event. If no response is received within the timeout, Feishu assumes the push failed and will retry, which causes your business logic to be executed repeatedly.

**Comprehensive Solutions**:
1. **Quick Response, Asynchronous Processing**: In your HTTP route handler, **respond with 200 OK immediately**, and then pass the event data to the background for asynchronous processing. This fundamentally avoids timeout retries caused by long processing times.
2. **Business-side Idempotency Design**: Even with quick responses, network jitters can still cause duplicate events. Therefore, designing for idempotency on the business side is crucial. Every Feishu event contains a unique identifier used for deduplication:
    1. **V2.0 Protocol Events**: `header.event_id`
    1. **V1.0 Protocol Events**: `uuid`

**Example: Combining Quick Response and Memory Deduplication (Use Redis for Production)**
```javascript
const processedEventIds = new Set<string>();
// Add deduplication logic in event handler
eventDispatcher.register({
    'im.message.receive_v1': async (event) => {
        const eventId = event.header.event_id;

if (processedEventIds.has(eventId)) {
            console.log(`Event ${eventId} already processed, skipping.`);
            return;
        }
        // ... Execute your business logic ...
        processedEventIds.add(eventId);

// Set a timer to clear old IDs to prevent infinite memory growth
        setTimeout(() => processedEventIds.delete(eventId), 5 * 60 * 1000); // Clear after 5 minutes
    },
});
```

### Handling Events Not Defined in SDK

Due to documentation synchronization delays or older versions, some event types might not be provided in the SDK's TypeScript definitions. In this case, you can register using the event's string name as the `key`. This is valid at runtime but will cause type check errors at compile time.

**Difference Explanation: Two Ways to Handle Unknown Events**
- **Method 1 (Simple & Direct): Use `@ts-ignore`**
  This is the fastest way; simply add `// @ts-ignore` above the registration code line to ignore TypeScript type errors.
- **Method 2 (Type Safe): Use Generics**
  If you want some type hints when handling unknown events, you can use generics on the `.register()` method to manually define the interface for the event body.

**Method 1: Use `@ts-ignore`**
```javascript
eventDispatcher.register({
    // @ts-ignore
    'approval.instance.status_changed_v4': async (data: any) => {
        console.log('Handling custom event:', data);
    }
});
```
**Method 2: Use Generics**
```typescript
interface MyCustomEventData {
    // Define interface based on actual event body
    approval_code: string;
    status: string;
}
eventDispatcher.register<{ 'approval.instance.create_v4'?: MyCustomEventData }>({
    'approval.instance.create_v4': async (data) => {
        // Here `data` will be inferred as MyCustomEventData type
        console.log(data.approval_code);
    }
});
```

### Sending and Updating Message Cards

- **Sending Cards**: Call `client.im.message.create`, set `msg_type` to `interactive`, and stringify the card JSON structure as `content`.
- **Updating Cards**: For sent interactive cards, you can use the `client.im.message.patch` method via `message_id` to update them. This is very useful for implementing delayed responses or multi-step interactions.

```javascript
// Example: Send and subsequently update a card
async function sendAndUpdateCard(chatId: string) {
    // 1. Send initial card
    const initialCard = { /* ... Card JSON ... */ };
    const createRes = await client.im.message.create({
        params: { receive_id_type: 'chat_id' },
        data: {
            receive_id: chatId,
            msg_type: 'interactive',
            content: JSON.stringify(initialCard),
        },
    });
    const messageId = createRes.data?.message_id;
    if (!messageId) return;
    // 2. After a 5-second delay, update the card using patch
    setTimeout(async () => {
        const updatedCard = { /* ... New Card JSON ... */ };
        await client.im.message.patch({
            path: { message_id: messageId },
            data: { content: JSON.stringify(updatedCard) },
        });
        console.log('Card updated successfully.');
    }, 5000);
}
```

### Card Interaction Callback Signature Verification Failed

If you are using the new Message Cards (Interactive Message Card 2.0) and encounter signature verification failures for interaction callbacks, this is usually because the SDK version is too low.
**Solution**: Please upgrade `@larksuiteoapi/node-sdk` to **`1.27.0` or higher**. This version is compatible with the signature verification logic for new cards.

```bash
# Check current version
npm list @larksuiteoapi/node-sdk

# Upgrade to latest version
npm install @larksuiteoapi/node-sdk@latest
```

### `fields` Field Format: Use Object instead of Map

When creating (`create`) or updating (`update`/`batchUpdate`) Bitable (Multidimensional Table) records, the `fields` field should be a **JavaScript Plain Object (Object)**, where `key` is the field name and `value` is the corresponding value.

```javascript
await client.bitable.appTableRecord.create({
  path: {
    app_token: 'YOUR_APP_TOKEN',
    table_id: 'YOUR_TABLE_ID',
  },
  data: {
    fields: {
      "TextField": "This is a string",
      "NumberField": 123,
      "SingleSelectField": "Option A",
    },
  },
});
```
**Note**: There might be incorrect examples in the API Explorer or old documentation using `Map` objects. This is incorrect. Please always use plain objects.

### Clearing Cells: Use `null`

To clear the content of one or more cells, set the value of the corresponding field to `null` when updating the record.
**Note**: Setting the field value to `undefined` is **invalid**. Such fields will be ignored in the request and cannot achieve the effect of clearing cells.

```javascript
await client.bitable.appTableRecord.update({
  path: {
    app_token: 'YOUR_APP_TOKEN',
    table_id: 'YOUR_TABLE_ID',
    record_id: 'recXXXXX',
  },
  data: {
    fields: {
      "FieldToClear": null,
      "AnotherFieldToClear": null,
    },
  },
});
```

### Handling Bitable Related Events

Bitable events (like record change `drive.file.bitable_record_changed_v1`) are also subscribed to and handled via `EventDispatcher`. If some events are missing from the SDK's type definitions, you can refer to the "Handling Events Not Defined in SDK" section above for manual registration.
To understand the JSON structure corresponding to various field types in `field_value`, please refer to the official Open Platform documentation: [Data Structure Overview](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/bitable/development-guide/bitable-structure).

### File Upload: Prioritize Using Stream

Whether uploading to the Drive (`drive.file.uploadAll`) or sending an image as a message attachment (`im.image.create`), it is **strongly recommended to prioritize using File Stream** instead of Buffer. Streams are more memory-efficient, especially suitable for large files, and effectively avoid memory overflows.

```javascript
import * as fs from 'fs';
const filePath = '/path/to/your/file.png';
const fileStream = fs.createReadStream(filePath);
const fileSize = fs.statSync(filePath).size;
await client.drive.file.uploadAll({
  data: {
    file_name: 'my-image.png',
    parent_type: 'explorer',
    parent_node: 'YOUR_FOLDER_TOKEN',
    size: fileSize,
    file: fileStream,
  },
});
```

### File Download/Export: Handling Returned Streams

For file downloads (`drive.file.download`) or sheet exports, starting from SDK `v1.37.0`, getting the file stream (`ReadableStream`) directly is supported. You can directly `pipe` it to a file write stream to efficiently process large files.

```javascript
import * as fs from 'fs';
const resp = await client.im.file.get({
    path: {
        file_key: 'file key',
    },
});
const readableStream = resp.getReadableStream();
const writableStream = fs.createWriteStream('file url');
readableStream.pipe(writableStream);
```

### Node.js v18+ File Upload Compatibility Strategy

In versions of `node-sdk` prior to `v1.17.1`, using Node.js v18+ and uploading files via `Buffer` might encounter `source.on is not a function` errors. This is because Node.js v18 introduced the native `Blob` type, causing compatibility issues in the internal logic of `axios`'s dependency library `form-data`.

**Best Practices and Solutions**
1. **Upgrade SDK (Strongly Recommended)**: Upgrade `@larksuiteoapi/node-sdk` to **`1.17.1` or higher**. This version has resolved this compatibility issue internally.
2. **Use Stream (Strongly Recommended)**: As mentioned above, always prioritize `fs.createReadStream` for file uploads. This is not only a best practice but also fundamentally avoids underlying differences between Node.js versions.
3. **Mitigation (If unable to upgrade)**: If you cannot upgrade the SDK temporarily, you can manually convert the `Buffer` to a `Stream` as a workaround.

**Mitigation Example: Buffer to Stream**
```javascript
import { Duplex } from 'stream';
function bufferToStream(buffer: Buffer): Duplex {
  const stream = new Duplex();
  stream.push(buffer);
  stream.push(null);
  return stream;
}
// Use during upload
// const fileBuffer = fs.readFileSync(filePath);
// const fileStream = bufferToStream(fileBuffer);
// ... Then pass fileStream in the API call
```

### How to Implement Custom Logging?

You can take over the SDK's log output by providing a custom `logger` for the `Client`. The `logger` needs to implement four methods: `debug`, `info`, `warn`, and `error`.

```javascript
import { Client, ILogger, LogLevel } from '@larksuiteoapi/node-sdk';
class MyCustomLogger implements ILogger {
    debug(message: any, ...args: any[]) { console.debug(`[SDK-DEBUG]`, message, ...args); }
    info(message: any, ...args: any[]) { console.info(`[SDK-INFO]`, message, ...args); }
    warn(message: any, ...args: any[]) { console.warn(`[SDK-WARN]`, message, ...args); }
    error(message: any, ...args: any[]) { console.error(`[SDK-ERROR]`, message, ...args); }
}
const client = new Client({
    appId: 'YOUR_APP_ID',
    appSecret: 'YOUR_APP_SECRET',
    logger: new MyCustomLogger(),
    logLevel: LogLevel.DEBUG, // Set log level, e.g., 'debug'
});
```
Additionally, combined with interceptors in a custom `axios` instance, you can implement more detailed HTTP request-level logging.