Command Palette

Search for a command to run...

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

api-client-development

БесплатноБез исполняемых скриптовНе проверен

Creating API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs

diegosouzapwот diegosouzapw★ 68 звёзд на 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

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 createClient, {type Client} from 'openapi-fetch';
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 = createClient<paths>({
    baseUrl: `https://${config.hostname}/api/v1`,
  });

  // 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 implementation details:

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

// 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 = createClient<paths>({
    baseUrl: `https://${config.shortCode}.api.commercecloud.salesforce.com/my-api/v1`,
  });

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

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

// Convert tenant ID to organization ID (adds f_ecom_ prefix)
toOrganizationId('zzxy_prd')        // Returns 'f_ecom_zzxy_prd'
toOrganizati
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

Вложенные файлы

metadata.json

FAQ

Что делает скилл api-client-development?

Creating API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs

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

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

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

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

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

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