| name | generate-sdk |
| description | Generate client SDKs from OpenAPI specs |
| shortcut | sdk |
Generate Client SDK
Automatically generate type-safe, production-ready client SDKs from OpenAPI/Swagger specifications for multiple programming languages with comprehensive features and documentation.
When to Use This Command
Use /generate-sdk when you need to:
- Create official client libraries for your API
- Ensure type safety across different programming languages
- Maintain SDK consistency with API changes
- Reduce manual SDK maintenance overhead
- Provide developers with intuitive API clients
- Support multiple programming languages
DON'T use this when:
- Your API lacks proper OpenAPI documentation (create spec first)
- Building internal-only APIs with single consumer (direct integration may be simpler)
- API is still rapidly changing (wait for stability)
Design Decisions
This command implements OpenAPI Generator as the primary approach because:
- Supports 50+ programming languages and frameworks
- Active community with regular updates
- Customizable templates for each language
- Generates both client and server code
- Comprehensive documentation generation
- Battle-tested in production environments
Alternative considered: Swagger Codegen
- Original OpenAPI code generator
- Less frequent updates
- Fewer customization options
- Recommended for legacy projects
Alternative considered: Custom generators
- Full control over generated code
- Better for specific requirements
- Higher maintenance burden
- Recommended only for unique needs
Prerequisites
Before running this command:
- Complete OpenAPI specification (v3.0 or v3.1)
- Validate spec with OpenAPI validators
- Define authentication schemes
- Document all endpoints and models
- Choose target languages and versions
Implementation Process
Step 1: Validate OpenAPI Specification
Ensure your OpenAPI spec is complete, valid, and includes all necessary details.
Step 2: Configure Generator Options
Set language-specific options like package names, versions, and dependencies.
Step 3: Generate SDK Code
Run the generator for each target language with customized templates.
Step 4: Add Custom Enhancements
Implement additional features like retry logic, caching, or specialized authentication.
Step 5: Package and Distribute
Create distribution packages for each language's package manager.
Output Format
The command generates:
sdks/javascript/ - Node.js/Browser SDK with TypeScript definitions
sdks/python/ - Python SDK with type hints
sdks/java/ - Java SDK with Maven/Gradle support
sdks/go/ - Go SDK with modules
docs/sdk-usage.md - Usage documentation for all SDKs
examples/ - Working examples for each language
Code Examples
Example 1: TypeScript SDK Generation and Usage
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:
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
import { Configuration, ProductsApi } from '@company/api-client';
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.();
Example 2: Python SDK Generation with Enhanced Features
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
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()
()
Example 3: Multi-Language SDK Generation Script
#!/bin/bash
SPEC_FILE="openapi.yaml"
OUTPUT_DIR="./sdks"
VERSION="1.0.0"
echo "Validating OpenAPI specification..."
npx @stoplight/spectral-cli lint $SPEC_FILE
if [ $? -ne 0 ]; then
echo "OpenAPI spec validation failed"
exit 1
fi
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
echo "Generating Python SDK..."
openapi-generator-cli generate \
-i $SPEC_FILE \
-g python \
-o $OUTPUT_DIR/python \
--additional-properties=\
packageName=company_api,\
packageVersion=$VERSION
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
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 Handling
| 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 |
Configuration Options
Generator Options
library: HTTP client library to use
dateLibrary: Date handling library
useSingleRequestParameter: Bundle parameters
nullableFields: Generate nullable types
enumUnknownDefaultCase: Handle unknown enums
Language-Specific Options
- TypeScript:
npmRepository, withoutPrefixEnums
- Python:
packageUrl, useNose, asyncio
- Java:
serializationLibrary, useRuntimeException
- Go:
isGoSubmodule, structPrefix
Best Practices
DO:
- Keep OpenAPI spec as single source of truth
- Version SDKs alongside API versions
- Include comprehensive examples
- Generate SDKs in CI/CD pipeline
- Add language-specific enhancements
- Publish to package registries
DON'T:
- Manually edit generated code (use templates)
- Skip OpenAPI validation before generation
- Ignore breaking changes in API
- Forget to update SDK documentation
- Mix generated and custom code
Performance Considerations
- Use connection pooling for better performance
- Implement client-side caching where appropriate
- Add request/response compression support
- Consider pagination for large result sets
- Implement circuit breakers for resilience
Related Commands
/api-documentation-generator - Generate API docs
/api-contract-generator - Create OpenAPI specs
/api-testing-framework - Test SDKs
/api-versioning-manager - Handle API versions
Version History
- v1.0.0 (2024-10): Initial implementation with OpenAPI Generator support
- Planned v1.1.0: Add GraphQL and gRPC SDK generation