Skip to content
Skills Library
Programming · Building & coding

api-client-development

/api-client-development

Creating typed API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs. Use when adding a new SCAPI client, generating types from an OpenAPI spec, setting up OAuth middleware, or integrating a new Commerce API endpoint.

Licence
Apache-2.0
Last repository change
23.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
4
Deprecation

No signals detected. Repository changed on 23.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What it does and when to use it

Creating typed API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs. Use when adding a new SCAPI client, generating types from an OpenAPI spec, setting up OAuth middleware, or integrating a new Commerce API endpoint.

Original author description

Creating typed API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs. Use when adding a new SCAPI client, generating types from an OpenAPI spec, setting up OAuth middleware, or integrating a new Commerce API endpoint.

How it works

  1. Overview
  2. Creating a New API Client
  3. SCAPI Client Pattern (OAuth Scope Injection)
  4. SCAPI Tenant ID Utilities
  5. OAuthStrategy.withAdditionalScopes()
  6. Complete SCAPI Client Example
  7. CLI Command Integration
  8. Testing API Clients
  9. Error Handling
  10. Troubleshooting
Original SKILL.md headings · 478 lines, 1,915 words
SKILL.md preview
---
name: api-client-development
description: Creating typed API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs. Use when adding a new SCAPI client, generating types from an OpenAPI spec, setting up OAuth middleware, or integrating a new Commerce API endpoint.
metadata:
  internal: true
---

# API Client Development

This skill covers creating typed API clients using OpenAPI specifications, with proper authentication and OAuth scope handling. It builds on the patterns in [SDK Module Development](../sdk-module-development/SKILL.md).

## Overview

API clients in this project use:
- **openapi-fetch**: Type-safe HTTP client generated from OpenAPI specs
- **openapi-typescript**: Generates TypeScript types from OpenAPI specs
- **Middleware pattern**: Auth and logging injected via openapi-fetch middleware
- **Shared transport**: every client is created with `createHttpClient(options, auth)` from `src/clients/http-transport.ts` (never openapi-fetch's `createClient`), so the transport options carried by the client's auth strategy apply

### Shared HTTP Transport (required)

TLS behavior such as the internal `selfsigned-api` mode is set on the `fetch` call (an undici dispatcher), not on the `Request`, so middleware cannot add it. The setting is **per config, not global**: strategies created from a resolved config (`createOAuth()`, `B2CInstance`, `resolveAuthStrategy`, `OAuthCommand`) carry `selfSignedApi`, `withAdditionalScopes()`/`withScopes()` preserve it, and clients built from the strategy inherit it. `src/clients/http-transport.ts` owns the policy:

- `createHttpClient<paths>(options, auth)` — use instead of openapi-fetch's `createClient`; pass the client's auth strategy. ESLint (`no-restricted-imports`) fails a direct default import of `openapi-fetch` in `src/`.
- `getApiFetch(auth)` — use instead of the global `fetch` for any direct OCAPI, SCAPI, Account Manager or MRT request (token calls, retries, hand-rolled requests). Pass the strategy or config the request belongs to. ESLint (`no-restricted-globals`) fails a bare `fetch` in `src/` outside an allowlist of non-B2C hosts.
- New strategies or config types that make API requests should accept `HttpTransportOptions` (`selfSignedApi`) and pass it through; a strategy wrapper must copy `selfSignedApi` from the strategy it wraps. Anything that does not receive it stays on strict TLS.
- APIs that take a dispatcher instead of a `fetch` (an auth strategy's `fetch()` init) use `getApiDispatcher(auth)`; WebSockets use `createApiWebSocket(url, auth)` (see `src/operations/mrt/tail-logs.ts`).
- SCAPI Admin APIs on `{shortCode}.api.commercecloud.salesforce.com` should use `buildScapiClient()` (`src/clients/scapi-client-factory.ts`), which already uses the shared transport plus auth, rate-limit and logging middleware.
- If a client needs a custom `fetch` option, call `getApiFetch(auth)` inside it (see `src/scapi/request.ts`).
- WebDAV is separate: `B2CInstance.webdav` uses `createWebDavDispatcher(tlsOptions)` from the same module, driven by `selfsigned`/client certificates, never by `selfSignedApi`.

## Creating a New API Client

### 1. Add the OpenAPI Spec

Place the spec in `packages/b2c-tooling-sdk/specs/`:

```
specs/
├── custom-apis-v1.yaml    # YAML or JSON
├── slas-admin-v1.yaml
└── ods-api-v1.json
```

### 2. Update Type Generation Script

In `packages/b2c-tooling-sdk/package.json`, add to the generate script:

```json
{
  "scripts": {
    "generate:types": "openapi-typescript specs/data-api.json -o src/clients/ocapi.generated.ts && openapi-typescript specs/newapi-v1.yaml -o src/clients/newapi.generated.ts"
  }
}
```

Run generation:

```bash
pnpm --filter @salesforce/b2c-tooling-sdk run generate:types
```

### 3. Create the Client Module

```typescript
// src/clients/newapi.ts
import type {Client} from 'openapi-fetch';
import {createHttpClient} from './http-transport.js';
import type {AuthStrategy} from '../auth/types.js';
import type {paths, components} from './newapi.generated.js';
import {createAuthMiddleware, createLoggingMiddleware} from './middleware.js';

// Re-export generated types for consumers
export type {paths, components};

// Client type alias
export type NewApiClient = Client<paths>;

// Config interface
export interface NewApiClientConfig {
  hostname: string;
  // Add API-specific config here
}

// Factory function
export function createNewApiClient(
  config: NewApiClientConfig,
  auth: AuthStrategy
): NewApiClient {
  const client = createHttpClient<paths>({
    baseUrl: `https://${config.hostname}/api/v1`,
  }, auth);

  // Middleware order: auth first (runs last), logging last (sees complete request)
  client.use(createAuthMiddleware(auth));
  client.use(createLoggingMiddleware('NEWAPI'));

  return client;
}
```

### 4. Export from Clients Barrel

```typescript
// src/clients/index.ts
export {createNewApiClient, type NewApiClient, type NewApiClientConfig} from './newapi.js';
export type {paths as NewApiPaths, components as NewApiComponents} from './newapi.js';
```

---

## SCAPI Client Pattern (OAuth Scope Injection)

SCAPI APIs require specific OAuth scopes. Instead of requiring CLI commands to manage scopes, **encapsulate scope logic in the client factory**.

### The Problem

Without encapsulation, CLI commands leak auth implementation details:

```typescript
// BAD: CLI command manages scopes
class MyCommand extends OAuthCommand {
  protected override loadConfiguration(): ResolvedConfig {
    const config = super.loadConfiguration();
    config.scopes = ['sfcc.custom-apis', `SALESFORCE_COMMERCE_API:${tenantId}`];
    return config;
  }
}
```

### The Solution

Use `OAuthStrategy.withAdditionalScopes()` in the client factory:

```typescript
// GOOD: Client encapsulates scope requirements
import {OAuthStrategy} from '../auth/oauth.js';
import type {AuthStrategy} from '../auth/types.js';

/** Default OAuth scopes required for this API */
export const MY_API_DEFAULT_SCOPES = ['sfcc.my-api'];

export interface MyApiClientConfig {
  shortCode: string;
  tenantId: string;           // Required for tenant-specific scope
  scopes?: string[];          // Optional override
}

export function createMyApiClient(
  config: MyApiClientConfig,
  auth: AuthStrategy
): MyApiClient {
  const client = createHttpClient<paths>({
    baseUrl: `https://${config.shortCode}.api.commercecloud.salesforce.com/my-api/v1`,
  }, auth);

  // Build required scopes: domain scope + tenant-specific scope
  const requiredScopes = config.scopes ?? [
    ...MY_API_DEFAULT_SCOPES,
    buildTenantScope(config.tenantId),
  ];

  // If OAuth strategy, add required scopes; otherwise use as-is (e.g., for testing)
  const scopedAuth = auth instanceof OAuthStrategy
    ? auth.withAdditionalScopes(requiredScopes)
    : auth;

  client.use(createAuthMiddleware(scopedAuth));
  client.use(createLoggingMiddleware('MY-API'));

  return client;
}
```

This pattern:
1. Keeps scope knowledge in the SDK, not the CLI
2. Allows scope override for special cases via `config.scopes`
3. Works with non-OAuth auth strategies (for testing/mocking)
4. CLI commands just pass the auth strategy through unchanged

---

## SCAPI Tenant ID Utilities

SCAPI APIs use an `organizationId` path parameter with the `f_ecom_` prefix, but OAuth scopes use the raw tenant ID. Use these utilities:

```typescript
// From @salesforce/b2c-tooling-sdk (or clients/custom-apis.ts)
import {toOrganizationId, normalizeTenantId, buildTenantScope} from '@salesforce/b2c-tooling-sdk';

// Convert tenant ID to organization ID (normalizes + adds f_ecom_ prefix)
toOrganizationId('zzxy_prd')        // Returns 'f_ecom_zzxy_prd'
toOrganizationId('f_ecom_zzxy_prd') // Returns 'f_ecom_zzxy_prd' (unchanged)
toOrganizationId('zzxy-prd')        // Returns 'f_ecom_zzxy_prd' (hyphen normalized)

// Normalize any tenant/org ID form to canonical underscore format
normalizeTenantId('f_ecom_zzxy_prd')                              // Returns 'zzxy_prd'
normalizeTenantId('zzxy-prd')                                     // Returns 'zzxy_prd'
normalizeTenantId('zzxy-prd.dx.commercecloud.salesforce.com')     // Returns 'zzxy_prd'

// Build tenant-specific OAuth scope (normalizes input)
buildTenantScope('zzxy_prd')        // Returns 'SALESFORCE_COMMERCE_API:zzxy_prd'
buildTenantScope('f_ecom_zzxy_prd') // Returns 'SALESFORCE_COMMERCE_API:zzxy_prd'
buildTenantScope('zzxy-prd')        // Returns 'SALESFORCE_COMMERCE_API:zzxy_prd'
```

### Constants

```typescript
/** Prefix required for SCAPI organizationId path parameter */
export const ORGANIZATION_ID_PREFIX = 'f_ecom_';

/** Prefix for tenant-specific SCAPI OAuth scopes */
export const SCAPI_TENANT_SCOPE_PREFIX = 'SALESFORCE_COMMERCE_API:';
```

---

## OAuthStrategy.withAdditionalScopes()

The `OAuthStrategy` class has a method for scope injection:

```typescript
// Creates a new OAuthStrategy with merged scopes
const scopedAuth = auth.withAdditionalScopes(['sfcc.custom-apis', 'SALESFORCE_COMMERCE_API:zzxy_prd']);
```

Key behaviors:
- Returns a **new** `OAuthStrategy` instance (immutable pattern)
- Merges scopes with deduplication (uses `Set`)
- The new strategy shares token cache with the original (keyed by clientId)
- If cached token doesn't have required scopes, it re-authenticates

---

## Complete SCAPI Client Example

Reference implementation: `packages/b2c-tooling-sdk/src/clients/custom-apis.ts`

```typescript
/*
 * Copyright (c) 2025, Salesforce, Inc.
 * SPDX-License-Identifier: Apache-2
 */
import type {Client} from 'openapi-fetch';
import {createHttpClient} from './http-transport.js';
import type {AuthStrategy} from '../auth/types.js';
import {OAuthStrategy} from '../auth/oauth.js';
import type {paths, components} from './custom-apis.generated.js';
import {createAuthMiddleware, createLoggingMiddleware} from './middleware.js';

export type {paths, components};
export type CustomApisClient = Client<paths>;

/** Default OAuth scopes required for Custom APIs */
export const CUSTOM_APIS_DEFAULT_SCOPES = ['sfcc.custom-apis'];

export interface CustomApisClientConfig {
  shortCode: string;
  tenantId: string;
  scopes?: string[];
}

export function createCustomApisClient(
  config: CustomApisClientConfig,
  auth: AuthStrategy
): CustomApisClient {
  const client = createHttpClient<paths>({
    baseUrl: `https://${config.shortCode}.api.commercecloud.salesforce.com/dx/custom-apis/v1`,
  }, auth);

  // Build required scopes: domain scope + tenant-specific scope
  const requiredScopes = config.scopes ?? [
    ...CUSTOM_APIS_DEFAULT_SCOPES,
    buildTenantScope(config.tenantId),
  ];

  // If OAuth strategy, add required scopes; otherwise use as-is
  const scopedAuth = auth instanceof OAuthStrategy
    ? auth.withAdditionalScopes(requiredScopes)
    : auth;

  client.use(createAuthMiddleware(scopedAuth));
  client.use(createLoggingMiddleware('CUSTOM-APIS'));

  return client;
}

// Tenant ID utilities
export const ORGANIZATION_ID_PREFIX = 'f_ecom_';
export const SCAPI_TENANT_SCOPE_PREFIX = 'SALESFORCE_COMMERCE_API:';

export function normalizeTenantId(value: string): string {
  let id = value.trim();
  if (id.includes('.')) id = id.split('.')[0];
  if (id.startsWith(ORGANIZATION_ID_PREFIX)) id = id.slice(ORGANIZATION_ID_PREFIX.length);
  return id.replaceAll('-', '_');
}

export function toOrganizationId(tenantId: string): string {
  return `${ORGANIZATION_ID_PREFIX}${normalizeTenantId(tenantId)}`;
}

export function buildTenantScope(tenantId: string): string {
  return `${SCAPI_TENANT_SCOPE_PREFIX}${normalizeTenantId(tenantId)}`;
}
```

---

## CLI Command Integration

With scope encapsulation in the client, CLI commands become simple:

```typescript
// packages/b2c-cli/src/commands/scapi/custom/status.ts
import {OAuthCommand} from '@salesforce/b2c-tooling-sdk/cli';
import {createCustomApisClient, toOrganizationId} from '@salesforce/b2c-tooling-sdk';

export default class ScapiCustomStatus extends OAuthCommand<typeof ScapiCustomStatus> {
  static flags = {
    ...OAuthCommand.baseFlags,
    'tenant-id': Flags.string({
      description: 'Organization/tenant ID',
      env: 'SFCC_TENANT_ID',
      required: true,
    }),
  };

  async run() {
    this.requireOAuthCredentials();

    const {'tenant-id': tenantId} = this.flags;
    const {shortCode} = this.resolvedConfig;

    // Auth strategy from base class - no scope configuration needed!
    const oauthStrategy = this.getOAuthStrategy();

    // Client handles scope injection internally
    const client = createCustomApisClient({shortCode, tenantId}, oauthStrategy);

    const {data, error} = await client.GET('/organizations/{organizationId}/endpoints', {
      params: {
        path: {organizationId: toOrganizationId(tenantId)},
      },
    });

    // Handle response...
  }
}
```

---

## Testing API Clients

Use MSW (Mock Service Worker) to mock API responses:

```typescript
import {http, HttpResponse} from 'msw';
import {setupServer} from 'msw/node';
import {createCustomApisClient} from '@salesforce/b2c-tooling-sdk';

const mockAuth: AuthStrategy = {
  async fetch(url, init) {
    return fetch(url, init);
  },
  async getAuthorizationHeader() {
    return 'Bearer mock-token';
  },
};

const server = setupServer(
  http.get('https://test.api.commercecloud.salesforce.com/dx/custom-apis/v1/organizations/*/endpoints', () => {
    return HttpResponse.json({
      data: [{apiName: 'test', status: 'active'}],
      total: 1,
      limit: 10,
    });
  })
);

beforeAll(() => server.listen());
afterAll(() => server.close());

it('fetches endpoints', async () => {
  const client = createCustomApisClient(
    {shortCode: 'test', tenantId: 'zzxy_prd'},
    mockAuth
  );

  const {data} = await client.GET('/organizations/{organizationId}/endpoints', {
    params: {path: {organizationId: 'f_ecom_zzxy_prd'}},
  });

  expect(data?.data).toHaveLength(1);
});
```

---

## Error Handling

When API requests fail, use `getApiErrorMessage()` to extract clean, user-friendly error messages. This utility handles multiple error formats and ensures HTML response bodies (like error pages from stopped sandboxes) are never shown to users.

### Using getApiErrorMessage

```typescript
import {getApiErrorMessage} from '@salesforce/b2c-tooling-sdk/clients';

const {data, error, response} = await client.GET('/sites', {...});

if (error) {
  // Returns structured error message or "HTTP 521 Web Server Is Down"
  const message = getApiErrorMessage(error, response);
  this.error(`Failed to fetch sites: ${message}`);
}
```

### Supported Error Patterns

The utility extracts messages from these patterns in priority order:

| API | Error Structure | Message Location |
|-----|-----------------|------------------|
| ODS/SLAS | `{ error: { message } }` | `error.error.message` |
| OCAPI | `{ fault: { message } }` | `error.fault.message` |
| SCAPI/Problem+JSON | `{ title, detail }` | `error.detail` or `error.title` |
| Standard Error | `{ message }` | `error.message` |
| Fallback | Any | `HTTP {status} {statusText}` |

### Why This Matters

**Without `getApiErrorMessage`:**
```
ERROR: Failed to fetch sites: <!DOCTYPE html><html lang="en"><head><title>521 - Sandbox Down</title>...
```

**With `getApiErrorMessage`:**
```
ERROR: Failed to fetch sites: HTTP 521 Web Server Is Down
```

### Important: Always Destructure `response`

When making API calls, always destructure the `response` object alongside `error`:

```typescript
// GOOD: Include response for error handling
const {data, error, response} = await client.GET('/endpoint', {...});

// BAD: Missing response - can't get clean error message
const {data, error} = await client.GET('/endpoint', {...});
```

---

## Troubleshooting

**OAuth scope errors (401/403 from SCAPI)**: Ensure the client factory calls `auth.withAdditionalScopes()` with both the domain scope (e.g., `sfcc.custom-apis`) and the tenant-specific scope (`SALESFORCE_COMMERCE_API:<tenantId>`). Use `buildTenantScope()` which normalizes any tenant ID form (hyphenated, hostname, org ID) to canonical underscores before building scopes.

**Type generation failures**: Check that the OpenAPI spec in `specs/` is valid YAML/JSON. Run `pnpm --filter @salesforce/b2c-tooling-sdk run generate:types` and inspect the output. Common issues: spec references external files that aren't present, or uses OpenAPI features not supported by openapi-typescript.

**Middleware ordering issues**: Auth middleware should be added first (`client.use(createAuthMiddleware(...))`), then logging. In openapi-fetch, middleware runs in reverse registration order for requests, so auth registered first means it runs last — ensuring the logging middleware sees the final request with auth headers.

**`organizationId` mismatch**: SCAPI path parameters need the `f_ecom_` prefix (use `toOrganizationId()`), while OAuth scopes need the raw tenant ID (use `normalizeTenantId()`). Both functions accept any parseable form (hyphenated, hostname, org ID). Mixing these up causes 404s or scope errors.

## Checklist: New SCAPI Client

1. Add OpenAPI spec to `specs/`
2. Update `generate:types` script in `package.json`
3. Run `pnpm --filter @salesforce/b2c-tooling-sdk run generate:types`
4. Create client module with:
   - `createHttpClient(options, auth)` (or `buildScapiClient()`) — never openapi-fetch's `createClient` or a bare `fetch`
   - Config interface including `tenantId`
   - Default scopes constant
   - Factory function with scope injection pattern
   - Tenant ID utilities (or import from existing)
5. Export from `src/clients/index.ts`
6. Add to main `src/index.ts` if needed
7. Write tests with MSW mocks
8. Build: `pnpm --filter @salesforce/b2c-tooling-sdk run build`
9. Test: `pnpm --filter @salesforce/b2c-tooling-sdk run test`

Versions

The database has no other skills named api-client-development.

Database snapshot: 13.11.2026 · package version f96064526c76 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100b2c-custom-api-development
    Develop Custom SCAPI REST endpoints with api.json routes, schema.yaml definitions, and OAuth scope configuration. Use this skill whenever the user needs to create a custom API on the Commerce platform, define OpenAPI 3.0 schemas for request/response, structure the rest-apis…
  • 95b2c-scapi-schemas
    Browse and retrieve SCAPI OpenAPI schema specifications. Use this skill whenever the user needs to list available SCAPI APIs, inspect endpoint paths or request/response shapes, explore data models for products or orders, check which fields an API returns, or understand SCAPI…
  • 100sf-b2c-scapi
    Build with Salesforce Commerce API (SCAPI) — Shopper APIs (Products, Search, Baskets, Orders, Customers), SLAS authentication, Commerce SDK for Node.js, rate limiting, pagination, and headless commerce patterns. This is the primary B2C API. Use when building headless storefronts or API integrations.
  • 100api-integrate
    Generate typed API clients and DTOs from OpenAPI/Swagger. Use when integrating an API or invoking /api-integrate.
  • 100openapi-codegen
    OpenAPI client code generation. Covers openapi-typescript, openapi-generator-cli, swagger-typescript-api, and trpc-openapi. Use for generating type-safe API clients. USE WHEN: user mentions "OpenAPI codegen", "generate API client", "openapi-typescript", "swagger-typescript-api",…
  • 100openapi-spec-generator
    Generate openapi spec generator operations. Auto-activating skill for API Development. Triggers on: openapi spec generator, openapi spec generator Part of the API Development skill category. Use when working with APIs or building integrations. Trigger with phrases like "openapi…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.