用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill generate-sdk命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Index of Build Systems Skills
Coordination patterns for distributed dataflow systems including barriers, epochs, and distributed snapshots
Windowing, sessionization, time-series aggregation, and late data handling for streaming systems
基于 SOC 职业分类
正在显示 SKILL.md
| name | generate-sdk |
| description | Generate client SDKs from OpenAPI specs |
| shortcut | sdk |
Automatically generate type-safe, production-ready client SDKs from OpenAPI/Swagger specifications for multiple programming languages with comprehensive features and documentation.
Use /generate-sdk when you need to:
DON'T use this when:
This command implements OpenAPI Generator as the primary approach because:
Alternative considered: Swagger Codegen
Alternative considered: Custom generators
Before running this command:
Ensure your OpenAPI spec is complete, valid, and includes all necessary details.
Set language-specific options like package names, versions, and dependencies.
Run the generator for each target language with customized templates.
Implement additional features like retry logic, caching, or specialized authentication.
Create distribution packages for each language's package manager.
The command generates:
sdks/javascript/ - Node.js/Browser SDK with TypeScript definitionssdks/python/ - Python SDK with type hintssdks/java/ - Java SDK with Maven/Gradle supportsdks/go/ - Go SDK with modulesdocs/sdk-usage.md - Usage documentation for all SDKsexamples/ - Working examples for each language# openapi.yaml
openapi: 3.0.0
info:
title: E-commerce API
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/products:
get:
operationId: listProducts
parameters:
- name: category
in: query
schema:
type: string
- name: limit
in: query
schema:
type: integer
default: 20
responses:
'200':
description: Product list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Product'
/products/{productId}:
get:
# Generate TypeScript SDK
npx @openapitools/openapi-generator-cli generate \
-i openapi.yaml \
-g typescript-axios \
-o ./sdks/typescript \
--additional-properties=\
npmName=@company/api-client,\
npmVersion=1.0.0,\
supportsES6=true,\
withInterfaces=true
// sdks/typescript/src/index.ts (generated)
import { Configuration, ProductsApi } from '@company/api-client';
// Enhanced configuration with retry and interceptors
export class ApiClient {
private config: Configuration;
private productsApi: ProductsApi;
private retryConfig = {
retries: 3,
retryDelay: 1000,
retryCondition: (error: any) => {
return error.response?.status >= 500;
}
};
constructor(apiKey?: string, basePath?: string) {
this.config = new Configuration({
basePath: basePath || 'https://api.example.com/v1',
accessToken: apiKey,
baseOptions: {
timeout: 10000,
headers: {
'User-Agent': '@company/api-client/1.0.0'
}
}
});
this.productsApi = (.);
.();
}
() {
... = [
{
.(, { data, headers });
data;
}
];
... = {
status >= && status < ;
};
}
(?: {
?: ;
?: ;
}): <[]> {
{
response = .(
..(
options?.,
options?.
)
);
response.;
} (error) {
.(error);
error;
}
}
(: ): <> {
{
response = .(
..(productId)
);
response.;
} (error) {
.(error);
error;
}
}
withRetry<T>(
: <T>,
retriesLeft = ..
): <T> {
{
();
} (error) {
(retriesLeft > && ..(error)) {
.(..);
.(fn, retriesLeft - );
}
error;
}
}
(: ): <> {
( (resolve, ms));
}
() {
(error.) {
.(, {
: error..,
: error..
});
} (error.) {
.(, error.);
} {
.(, error.);
}
}
}
client = ();
products = client.({
: ,
:
});
product = client.();
# Generate Python SDK
openapi-generator-cli generate \
-i openapi.yaml \
-g python \
-o ./sdks/python \
--additional-properties=\
packageName=company_api,\
packageVersion=1.0.0,\
projectName=company-api-client
# sdks/python/company_api/enhanced_client.py
import time
import logging
from typing import Optional, Dict, Any, List
from functools import wraps
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from company_api import Configuration, ApiClient
from company_api.api import ProductsApi
from company_api.models import Product
logger = logging.getLogger(__name__)
def retry_on_failure(max_retries=3, delay=1):
"""Decorator for retrying failed API calls."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_exception = None
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
last_exception = e
if attempt < max_retries - 1:
wait_time = delay * (2 ** attempt)
logger.warning(
)
time.sleep(wait_time)
:
logger.error()
last_exception
wrapper
decorator
:
():
config = Configuration()
config.host = base_url
api_key:
config.api_key[] = api_key
config.api_key_prefix[] =
session = requests.Session()
retry_strategy = Retry(
total=max_retries,
backoff_factor=,
status_forcelist=[, , , , ],
)
adapter = HTTPAdapter(
max_retries=retry_strategy,
pool_connections=,
pool_maxsize=
)
session.mount(, adapter)
session.mount(, adapter)
.api_client = ApiClient(configuration=config)
.api_client.rest_client.session = session
.products_api = ProductsApi(.api_client)
.timeout = timeout
._cache: [, ] = {}
() -> [Product]:
cache_key =
use_cache cache_key ._cache:
logger.info()
._cache[cache_key]
:
response = .products_api.list_products(
category=category,
limit=limit,
_request_timeout=.timeout
)
use_cache:
._cache[cache_key] = response
logger.info()
response
Exception e:
logger.error()
() -> Product:
cache_key =
use_cache cache_key ._cache:
logger.info()
._cache[cache_key]
:
response = .products_api.get_product(
product_id=product_id,
_request_timeout=.timeout
)
use_cache:
._cache[cache_key] = response
logger.info()
response
Exception e:
logger.error()
():
pattern:
keys_to_remove = [
k k ._cache.keys()
pattern k
]
key keys_to_remove:
._cache[key]
logger.info()
:
._cache.clear()
logger.info()
__name__ == :
logging.basicConfig(level=logging.INFO)
client = EnhancedApiClient(
api_key=,
timeout=,
max_retries=
)
products = client.list_products(
category=,
limit=,
use_cache=
)
()
product = client.get_product()
()
#!/bin/bash
# generate-all-sdks.sh
SPEC_FILE="openapi.yaml"
OUTPUT_DIR="./sdks"
VERSION="1.0.0"
# Validate OpenAPI spec first
echo "Validating OpenAPI specification..."
npx @stoplight/spectral-cli lint $SPEC_FILE
if [ $? -ne 0 ]; then
echo "OpenAPI spec validation failed"
exit 1
fi
# Generate TypeScript SDK
echo "Generating TypeScript SDK..."
npx @openapitools/openapi-generator-cli generate \
-i $SPEC_FILE \
-g typescript-axios \
-o $OUTPUT_DIR/typescript \
--additional-properties=\
npmName=@company/api-client,\
npmVersion=$VERSION,\
supportsES6=true,\
withInterfaces=true
# Generate Python SDK
echo "Generating Python SDK..."
openapi-generator-cli generate \
-i $SPEC_FILE \
-g python \
-o $OUTPUT_DIR/python \
--additional-properties=\
packageName=company_api,\
packageVersion=$VERSION
# Generate Java SDK
echo "Generating Java SDK..."
openapi-generator-cli generate \
-i $SPEC_FILE \
-g java \
-o $OUTPUT_DIR/java \
--additional-properties=\
groupId=com.company,\
artifactId=api-client,\
artifactVersion=$VERSION,\
library=okhttp-gson
# Generate Go SDK
echo "Generating Go SDK..."
openapi-generator-cli generate \
-i $SPEC_FILE \
-g go \
-o $OUTPUT_DIR/go \
--additional-properties=\
packageName=company,\
packageVersion=
lang typescript python java go;
>> /README.md
>> /README.md
| Error | Cause | Solution |
|---|---|---|
| "Invalid OpenAPI spec" | Malformed specification | Validate with Spectral or similar tools |
| "Unsupported feature" | Generator limitation | Check generator documentation for support |
| "Template error" | Custom template issues | Review template syntax and variables |
| "Version conflict" | Dependency issues | Update generator and dependencies |
| "Generation failed" | Missing required fields | Ensure all required spec fields are present |
Generator Options
library: HTTP client library to usedateLibrary: Date handling libraryuseSingleRequestParameter: Bundle parametersnullableFields: Generate nullable typesenumUnknownDefaultCase: Handle unknown enumsLanguage-Specific Options
npmRepository, withoutPrefixEnumspackageUrl, useNose, asyncioserializationLibrary, useRuntimeExceptionisGoSubmodule, structPrefixDO:
DON'T:
/api-documentation-generator - Generate API docs/api-contract-generator - Create OpenAPI specs/api-testing-framework - Test SDKs/api-versioning-manager - Handle API versions