# @drupal-api-client/json-api-client 中文文档

规范地址：https://npmcn.com/package/%40drupal-api-client/json-api-client/

版本：1\.5\.0
npm 元数据更新时间：2026-08-07T20:15:48.698Z
中文译文更新时间：2026-11-12T20:47:52.736Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40drupal-api-client/json-api-client
原文对照：https://npmcn.com/package/%40drupal-api-client/json-api-client/?lang=original
项目主页：https://project.pages.drupalcode.org/api_client/
源码仓库：https://git.drupalcode.org/project/api_client

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：66.2 kB，7 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：5 个
- 首次发布：2023-10-26T15:15:02.798Z
- 最新版本发布：2026-08-07T20:15:48.479Z
- 近 30 天下载量：18089（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：19（近 12 个月 3 个）

## 中文简介

简化与 Drupal 的 JSON: API 端点交互进程的软件包

## 安装

```sh
npm install @drupal-api-client/json-api-client
```

也可以使用：`pnpm add @drupal-api-client/json-api-client`、`yarn add @drupal-api-client/json-api-client`、`bun add @drupal-api-client/json-api-client`

## README

# jsonapi 客户端

此软件包包含 `JsonApiClient` 扩展基数的类 `ApiClient` 类从 `@drupal-api-client/api-client` 软件包。 见 [https://www.drupal.org/project/api 客户端](https://www.drupal.org/project/api_client) 欲了解该项目的更多信息.

## 安装

```shell
npm i @drupal-api-client/json-api-client
```

## 使用量

```ts
import {
  JsonApiClient,
  createCache,
  DefaultSerializer,
} from "@drupal-api-client/json-api-client";
import Jsona from "jsona";

// the baseUrl to fetch data from
const myDrupalUrl = process.env.MY_DRUPAL_SITE || "https://drupal.example.com";

const nodeCache = new NodeCache();

const client = new JsonApiClient(myDrupalUrl, {
  // supply a custom fetch method in order to add  certain headers to each request
  // or any other logic you may need before the fetch call
  customFetch: (input: RequestInfo | URL, init?: RequestInit) => {
    const newHeaders = new Headers(init?.headers);
    newHeaders.set("X-Custom-Header", "my-custom-value");
    const newInit = {
      ...init,
      headers: newHeaders,
    };

    return fetch(input, newInit);
  },
  // the optional cache will cache a request and return the cached data if the request
  // is made again with the same type same data.
  // The cache must implement the `Cache` interface.
  // The `createCache` method provides a default cache that satisfies this interface.
  cache: createCache(),
  // the optional authentication object will be used to authenticate requests.
  // Currently Basic auth is supported.
  authentication: {
    type: "Basic",
    // It is recommended to store sensitive information in environment variables that
    // are not checked in to the source code.
    credentials: {
      username: process.env.MY_USERNAME,
      password: process.env.MY_SECRET_PASSWORD,
    },
  },
  // The language used for any request that does not pass its own `locale`
  // option (a per-request `locale` always wins). The language is sent as a
  // `/{locale}/` URL prefix (how stock Drupal negotiates, see
  // languagePathPrefix below) and as a `langCode` query parameter (the only
  // language selector of the jsonapi_multilingual module; stock Drupal
  // ignores it), so the same request works on either kind of backend.
  // With jsonapi_multilingual, a read of a translation that does not exist
  // is a strict 404 advertising the existing translations (see
  // getAvailableTranslations); pass the `includeFallback: true` read option
  // to defer to the site's language fallback chain instead.
  // example read: https://drupal.example.com/en/jsonapi/node/article?langCode=en
  // Omit it to let the backend serve its own default language.
  defaultLocale: "en",
  // The `/{locale}/` prefix is sent for backwards compatibility with URL
  // path-prefix negotiation (stock Drupal). For a backend using the
  // jsonapi_multilingual module, setting this to false is recommended:
  // langCode then carries the language on the canonical URL. This includes
  // the decoupled_router hop of getResourceByPath — a translated alias
  // resolves from the path alone, and the module reports the resolved
  // language as entity.langcode, which getResourceByPath passes to the
  // follow-up read. On a backend without the module, leave this on if
  // translated path aliases must resolve.
  languagePathPrefix: true,
  // the optional serializer will be used to serialize and deserialize data.
  // DefaultSerializer (from this package) extends Jsona and adds getMeta()/getLinks() for
  // JSON:API top-level meta and links; otherwise use Jsona() or another compatible serializer.
  serializer: new DefaultSerializer(),
  // when set to true, verbose logging will be output to the console,
  // helpful for debugging errors.
  debug: true,
});

try {
  // fetch a single resource
  const article = await client.getResource("node--article", "1234");

  // fetch a collection of nodes
  const articles = await client.getCollection("node--article");
} catch (error) {
  // errors will be bubbled up from the `getCollection` and `getResource` methods.
  // if `debug` is set to true in the options, the error will be logged to the console.
  // You can handle the error here as you see fit.
}
```

## 常见问题

### @drupal-api-client/json-api-client 是什么？

简化与 Drupal 的 JSON: API 端点交互进程的软件包

### 如何安装 @drupal-api-client/json-api-client？

在项目目录运行 npm install @drupal-api-client/json-api-client，或使用 pnpm add / yarn add / bun add。

### @drupal-api-client/json-api-client 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @drupal-api-client/json-api-client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @drupal-api-client/json-api-client 可以商用吗？

@drupal-api-client/json-api-client 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @drupal-api-client/json-api-client 的下载量有多少？

根据 npm 官方下载统计，@drupal-api-client/json-api-client 在 2026/10/13 – 2026/11/11 这 30 天内被下载 18,089 次，日均约 603 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @drupal-api-client/json-api-client 还在维护吗？

最新版本 1\.5\.0 发布于 2026/08/08（3 个月前）；至今共发布 19 个版本，其中过去 12 个月发布了 3 个；首次发布于 2023/10/26。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

