@contentful/optimization-api-client

中文文档
2.2.3发布于 2026/11/06MITTypeScriptESM + CJS近 30 天下载 8298

API client for Contentful Optimization services

原始使用文档
文档目录10 节
  1. API Client
  2. Getting started
  3. When to use this package
  4. Common configuration
  5. API surface
  6. Experience API
  7. Insights API
  8. Schema entry point
  9. Fetch helpers
  10. Related

Contentful Logo

Contentful Personalization & Analytics

API Client

The Contentful Optimization API Client provides low-level transport for the Experience API and Insights API. Application-facing SDKs compose this package with event builders, state management, queueing, and runtime-specific defaults.

We recommend starting applications with Web, React Web, Node, or React Native SDKs. Use this package directly when building or maintaining SDK layers, tests, tooling, or first-party integrations that need raw API access.

[!IMPORTANT]

Upgrading from v1? Follow the v1-to-v2 migration guide before changing package versions or route-dependent infrastructure.

Table of Contents

Getting started

Install using an NPM-compatible package manager, pnpm for example:

pnpm install @contentful/optimization-api-client

Import and initialize the unified API client; both CJS and ESM module systems are supported, ESM preferred:

import { ApiClient } from '@contentful/optimization-api-client'

const client = new ApiClient({
  spaceId: 'your-space-id',
  environment: 'master',
})

When to use this package

Use @contentful/optimization-api-client when you need direct low-level access to the Experience API or Insights API transport surface. Use an application-facing SDK when you need optimization state, consent handling, event builders, entry resolution, tracking, or platform defaults.

Common configuration

OptionRequired?DefaultDescription
spaceIdYesN/AContentful Space identifier for Experience and Insights API requests
environmentNo'master'Contentful space environment identifier for Experience and Insights APIs
experienceNoSee Experience options belowExperience API endpoint and default request options
insightsNoSee Insights options belowInsights API endpoint options
fetchOptionsNoSDK defaultsFetch timeout and retry behavior

Common Experience API options:

OptionRequired?DefaultDescription
baseUrlNo'https://experience.ninetailed.co/'Base URL for the Experience API
enabledFeaturesNo['ip-enrichment', 'location']Experience API features for mutation requests
ipNoundefinedIP address override for Experience API analysis
localeNoAPI defaultLocale query parameter for localized responses
locationNoAPI fallbackRequest location default for single-profile mutations
plainTextNoEndpoint-specificSends single-profile mutation endpoints as text
preflightNofalseAggregates a profile state without storing it

Experience mutation request options except baseUrl can also be provided per mutation request. getProfile is a read request and only uses locale from per-call options; mutation-only options such as enabledFeatures, ip, location, plainText, and preflight do not apply. Single-profile mutation requests default to plainText: true and send text/plain unless overridden. Batch profile updates with upsertManyProfiles are the JSON-default exception and use plainText: false by default. locale is sent as the Experience API locale query parameter and can localize profile fields such as location.city and location.country. Higher-level SDK merge-tag helpers resolve against the profile values returned by the Experience API, so applications that render localized Contentful entries commonly pass the same locale used for the CDA entry fetch. Pass a valid locale tag; invalid locale syntax can fail Experience API request validation. See Locale handling in the Optimization SDK Suite for how this request locale relates to Contentful and SDK-resolved locales.

Common Insights API options:

OptionRequired?DefaultDescription
baseUrlNo'https://ingest.insights.ninetailed.co/'Base URL for the Insights API

Common fetchOptions are fetchMethod, requestTimeout, retries, intervalTimeout, onFailedAttempt, and onRequestTimeout. Default retries intentionally apply only to HTTP 503 responses.

For every option, callback payload, request type, and response type, use the generated API Client reference.

API surface

Experience API

Experience API methods are scoped to client.experience and return profile and optimization data:

const { profile, selectedOptimizations, changes } = await client.experience.upsertProfile(
  {
    profileId: 'f0837d7dc6344c36a3a0a06c4cde754b',
    events: [pageEvent],
  },
  { locale: 'de-DE' },
)

Common methods include getProfile, createProfile, updateProfile, upsertProfile, and upsertManyProfiles.

Applications can configure request location through their normal SDK's api.location option. Stateless Node integrations can override it per request through forRequest({ experienceOptions: { location } }); see the Node SDK configuration and Web SDK configuration. The direct transport example below is for SDK-layer and tooling consumers.

For createProfile, updateProfile, and upsertProfile, set location in the Experience client configuration or in per-request options:

import { ExperienceApiClient } from '@contentful/optimization-api-client'

const experience = new ExperienceApiClient({
  spaceId: 'your-space-id',
  environment: 'master',
  location: { countryCode: 'DE', country: 'Germany' },
})

await experience.createProfile({ events: [pageEvent] })
await experience.upsertProfile(
  { profileId: 'f0837d7dc6344c36a3a0a06c4cde754b', events: [pageEvent] },
  {
    location: {
      countryCode: 'FR',
      country: 'France',
      city: 'Paris',
      coordinates: { latitude: 48.8566, longitude: 2.3522 },
    },
  },
)

With the unified ApiClient, place the constructor default under experience.location. A per-request location replaces the entire constructor default; the client does not merge them. The backend merges each event's context.location over the resolved request location, so event fields override matching request fields. If neither source supplies a location, existing backend fallback behavior applies, including Cloudflare request geolocation when enabled.

Pass location: {} to override the constructor default and supply an empty request-location default instead of Cloudflare geolocation. This does not erase an existing profile location. The backend selects profile location from the latest timestamped event with a non-empty location in the batch, falling back to the existing profile location when none is available. Request location affects evaluation and profile updates; it is not a permanent location lock. The ip option controls IP enrichment through X-Force-IP and does not control profile geolocation.

upsertManyProfiles does not send request-level location, including a constructor default. For batch updates, supply location through each event's context.location.

For how these inputs affect profile continuity across later server and browser requests, see Location inputs and profile updates.

Insights API

Insights API methods are scoped to client.insights and send event batches with a full Profile returned by the Experience API:

await client.insights.sendBatchEvents([
  {
    profile,
    events: [viewEvent],
  },
])

Insights endpoints do not return response data. For last-chance browser lifecycle delivery, pass a per-call beacon sender that receives the request URL and already serialized body.

A true result means Beacon queue acceptance or a successful HTTP response when using fetch. Beacon acceptance does not confirm service delivery; neither result proves Analytics persistence.

Schema entry point

@contentful/optimization-api-client/api-schemas owns the Experience API and Insights API runtime validation schemas, inferred types, and validation helpers used by this client. Import those contracts from that entry point when building SDK layers, tooling, or tests:

import { ExperienceResponse } from '@contentful/optimization-api-client/api-schemas'

This entry point does not include Contentful CDA schemas. Import CDA schemas from @contentful/optimization-core/api-schemas instead. That Core entry point also provides an aggregate schema surface for SDK layers that need both CDA and API contracts.

ExO interaction events use the Experience and ExperienceFragment entity kinds. They accept parentVariantId for the root Experience's selected variant, including default for its baseline. This is separate from the rendered entity's own variantId. SDK event builders supply these values; the schemas preserve them during request serialization and accept older events that omit them.

Fetch helpers

This package also exports fetch helper functions used by SDK layers:

HelperPurpose
createProtectedFetchMethodAdds timeout and retry protection around a fetch method
createRetryFetchMethodApplies retry policy to retryable responses
createTimeoutFetchMethodAborts requests after the configured timeout

Use generated reference docs for helper signatures and callback payloads.

版本与发布记录

@contentful/optimization-api-client 共发布 27 个版本,首次发布于 2026/02/03;过去 12 个月发布了 27 个版本。

版本发布日期距今
2.2.3latest2026/11/064 天前
2.2.22026/11/046 天前
2.2.12026/10/2220 天前
2.2.02026/10/1922 天前
2.1.02026/10/1625 天前
2.0.12026/09/231 个月前

其他发布通道:alpha → 0.1.0-alpha。

关于 @contentful/optimization-api-client 的常见问题

@contentful/optimization-api-client 是什么?

API client for Contentful Optimization services

如何安装 @contentful/optimization-api-client?

在项目目录运行 npm install @contentful/optimization-api-client,或使用 pnpm add / yarn add / bun add。

@contentful/optimization-api-client 支持 TypeScript 吗?

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

@contentful/optimization-api-client 支持 ESM 还是 CommonJS?

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

@contentful/optimization-api-client 可以商用吗?

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

@contentful/optimization-api-client 的下载量有多少?

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

@contentful/optimization-api-client 还在维护吗?

最新版本 2.2.3 发布于 2026/11/06(4 天前);至今共发布 27 个版本,其中过去 12 个月发布了 27 个;首次发布于 2026/02/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。