| name | api-client-development |
| description | Creating API clients with OpenAPI specs, authentication, and OAuth scopes for SCAPI and similar APIs |
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
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';
export type {paths, components};
export type NewApiClient = Client<paths>;
export interface NewApiClientConfig {
hostname: string;
}
export function createNewApiClient(
config: NewApiClientConfig,
auth: AuthStrategy
): NewApiClient {
const client = createClient<paths>({
baseUrl: `https://${config.hostname}/api/v1`,
});
client.((auth));
client.(());
client;
}
4. Export from Clients Barrel
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:
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:
import {OAuthStrategy} from '../auth/oauth.js';
import type {AuthStrategy} from '../auth/types.js';
export const MY_API_DEFAULT_SCOPES = ['sfcc.my-api'];
export interface MyApiClientConfig {
shortCode: string;
tenantId: string;
scopes?: string[];
}
export function createMyApiClient(
config: MyApiClientConfig,
auth: AuthStrategy
): MyApiClient {
const client = createClient<paths>({
baseUrl: `https://${config.shortCode}.api.commercecloud.salesforce.com/my-api/v1`,
});
const requiredScopes = config.scopes ?? [
...MY_API_DEFAULT_SCOPES,
buildTenantScope(config.tenantId),
];
scopedAuth = auth
? auth.(requiredScopes)
: auth;
client.((scopedAuth));
client.(());
client;
}
This pattern:
- Keeps scope knowledge in the SDK, not the CLI
- Allows scope override for special cases via
config.scopes
- Works with non-OAuth auth strategies (for testing/mocking)
- 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:
import {toOrganizationId, toTenantId, buildTenantScope} from '@salesforce/b2c-tooling-sdk';
toOrganizationId('zzxy_prd')
toOrganizationId('f_ecom_zzxy_prd')
toTenantId('f_ecom_zzxy_prd')
toTenantId('zzxy_prd')
buildTenantScope('zzxy_prd')
buildTenantScope('f_ecom_zzxy_prd')
Constants
export const ORGANIZATION_ID_PREFIX = 'f_ecom_';
export const SCAPI_TENANT_SCOPE_PREFIX = 'SALESFORCE_COMMERCE_API:';
OAuthStrategy.withAdditionalScopes()
The OAuthStrategy class has a method for scope injection:
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
import createClient, {type Client} from 'openapi-fetch';
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>;
export const CUSTOM_APIS_DEFAULT_SCOPES = ['sfcc.custom-apis'];
export interface CustomApisClientConfig {
shortCode: string;
tenantId: string;
scopes?: string[];
}
export function createCustomApisClient(
config: CustomApisClientConfig,
auth:
): {
client = createClient<paths>({
: ,
});
requiredScopes = config. ?? [
...,
(config.),
];
scopedAuth = auth
? auth.(requiredScopes)
: auth;
client.((scopedAuth));
client.(());
client;
}
= ;
= ;
(): {
tenantId.()
? tenantId
: ;
}
(): {
value.()
? value.(.)
: value;
}
(): {
;
}
CLI Command Integration
With scope encapsulation in the client, CLI commands become simple:
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;
const oauthStrategy = this.getOAuthStrategy();
const client = createCustomApisClient({shortCode, tenantId}, oauthStrategy);
{data, error} = client.(, {
: {
: {: (tenantId)},
},
});
}
}
Testing API Clients
Use MSW (Mock Service Worker) to mock API responses:
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 = (
{: , : },
mockAuth
);
{data} = client.(, {
: {: {: }},
});
(data?.).();
});
Checklist: New SCAPI Client
- Add OpenAPI spec to
specs/
- Update
generate:types script in package.json
- Run
pnpm --filter @salesforce/b2c-tooling-sdk run generate:types
- Create client module with:
- Config interface including
tenantId
- Default scopes constant
- Factory function with scope injection pattern
- Tenant ID utilities (or import from existing)
- Export from
src/clients/index.ts
- Add to main
src/index.ts if needed
- Write tests with MSW mocks
- Build:
pnpm --filter @salesforce/b2c-tooling-sdk run build
- Test:
pnpm --filter @salesforce/b2c-tooling-sdk run test