Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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…

SalesforceCommerceCloudот SalesforceCommerceCloud★ 58 звёзд на GitHub

Об этом скилле

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.

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:

{
  "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:

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

3. Create the Client Module

// 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

// 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 impleme

Полный SKILL.md на GitHub

Установить api-client-development в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл 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.

Как установить скилл api-client-development?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл api-client-development запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить api-client-development с