File size: 13,157 Bytes
50a7bf0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 |
# Client SDK Generation Guide
This guide explains how to generate and use client SDKs for the Video Generation API.
## Overview
The Video Generation API supports automatic client SDK generation in multiple programming languages using OpenAPI Generator. This allows developers to quickly integrate with the API using idiomatic code in their preferred language.
## Supported Languages
- **TypeScript/JavaScript** - Modern TypeScript client with fetch API
- **Python** - Python client with requests library
- **Java** - Java client with OkHttp and Gson
- **C#** - .NET Standard 2.0 compatible client
- **Go** - Go client with native HTTP library
- **PHP** - PHP client with Guzzle HTTP
- **Ruby** - Ruby client with Faraday HTTP
## Prerequisites
### Required Tools
1. **Node.js and npm** - For OpenAPI Generator CLI
2. **OpenAPI Generator CLI** - For generating clients
3. **Language-specific tools** (optional, for testing):
- TypeScript: Node.js, npm
- Python: Python 3.7+, pip
- Java: JDK 8+, Maven
- C#: .NET Core SDK
- Go: Go 1.16+
- PHP: PHP 7.4+, Composer
- Ruby: Ruby 2.7+, Bundler
### Installation
Install OpenAPI Generator CLI:
```bash
npm install -g @openapitools/openapi-generator-cli
```
## Quick Start
### Using the Python Script
The easiest way to generate clients is using the provided Python script:
```bash
# Generate all supported clients
python scripts/generate_clients.py
# Generate specific languages
python scripts/generate_clients.py --languages typescript python
# Use custom API URL
python scripts/generate_clients.py --api-url https://api.example.com
# Custom output directory
python scripts/generate_clients.py --output-dir my_clients
```
### Using the Shell Script
Alternatively, use the shell script:
```bash
# Generate all clients
./scripts/generate_clients.sh
# Generate specific languages
./scripts/generate_clients.sh typescript python java
# Use custom API URL
./scripts/generate_clients.sh --api-url https://api.example.com typescript
```
### Manual Generation
For manual control, use OpenAPI Generator CLI directly:
```bash
# Fetch OpenAPI specification
curl -o openapi.json http://localhost:8000/openapi.json
# Generate TypeScript client
openapi-generator-cli generate \
-i openapi.json \
-g typescript-fetch \
-o clients/typescript \
--package-name video-api-client
# Generate Python client
openapi-generator-cli generate \
-i openapi.json \
-g python \
-o clients/python \
--package-name video_api_client
```
## Generated Client Structure
Each generated client includes:
```
clients/
βββ typescript/
β βββ src/
β β βββ apis/
β β βββ models/
β β βββ index.ts
β βββ package.json
β βββ README.md
β βββ example.ts
βββ python/
β βββ video_api_client/
β β βββ api/
β β βββ models/
β β βββ __init__.py
β βββ setup.py
β βββ README.md
β βββ example.py
βββ ...
```
## Usage Examples
### TypeScript
```typescript
import { Configuration, VideosApi } from 'video-api-client';
const config = new Configuration({
basePath: 'https://api.example.com',
accessToken: 'your-clerk-session-token'
});
const videosApi = new VideosApi(config);
async function generateVideo() {
try {
const jobResponse = await videosApi.createVideoGenerationJob({
configuration: {
topic: "Pythagorean Theorem",
context: "Explain the mathematical proof",
quality: "medium",
use_rag: true
}
});
console.log('Job created:', jobResponse.job_id);
// Poll for completion
let status = 'queued';
while (status !== 'completed' && status !== 'failed') {
await new Promise(resolve => setTimeout(resolve, 5000));
const statusResponse = await videosApi.getVideoJobStatus(jobResponse.job_id);
status = statusResponse.status;
console.log(`Status: ${status} (${statusResponse.progress.percentage}%)`);
}
if (status === 'completed') {
const videoBlob = await videosApi.downloadVideoFile(jobResponse.job_id);
console.log('Video downloaded');
}
} catch (error) {
console.error('Error:', error);
}
}
```
### Python
```python
import time
from video_api_client import Configuration, ApiClient, VideosApi
from video_api_client.models import JobCreateRequest, JobConfiguration
configuration = Configuration(
host="https://api.example.com",
access_token="your-clerk-session-token"
)
with ApiClient(configuration) as api_client:
videos_api = VideosApi(api_client)
try:
# Create job
job_request = JobCreateRequest(
configuration=JobConfiguration(
topic="Pythagorean Theorem",
context="Explain the mathematical proof",
quality="medium",
use_rag=True
)
)
job_response = videos_api.create_video_generation_job(job_request)
print(f"Job created: {job_response.job_id}")
# Poll for completion
status = "queued"
while status not in ["completed", "failed"]:
time.sleep(5)
status_response = videos_api.get_video_job_status(job_response.job_id)
status = status_response.status
print(f"Status: {status} ({status_response.progress.percentage}%)")
if status == "completed":
video_data = videos_api.download_video_file(job_response.job_id)
with open("video.mp4", "wb") as f:
f.write(video_data)
print("Video downloaded")
except Exception as e:
print(f"Error: {e}")
```
### Java
```java
import com.example.videoapiclient.ApiClient;
import com.example.videoapiclient.Configuration;
import com.example.videoapiclient.api.VideosApi;
import com.example.videoapiclient.model.*;
public class VideoApiExample {
public static void main(String[] args) {
ApiClient client = Configuration.getDefaultApiClient();
client.setBasePath("https://api.example.com");
client.setAccessToken("your-clerk-session-token");
VideosApi videosApi = new VideosApi(client);
try {
JobConfiguration config = new JobConfiguration()
.topic("Pythagorean Theorem")
.context("Explain the mathematical proof")
.quality(VideoQuality.MEDIUM)
.useRag(true);
JobCreateRequest request = new JobCreateRequest().configuration(config);
JobResponse jobResponse = videosApi.createVideoGenerationJob(request);
System.out.println("Job created: " + jobResponse.getJobId());
// Poll for completion
String status = "queued";
while (!"completed".equals(status) && !"failed".equals(status)) {
Thread.sleep(5000);
JobStatusResponse statusResponse = videosApi.getVideoJobStatus(jobResponse.getJobId());
status = statusResponse.getStatus().getValue();
System.out.println("Status: " + status + " (" +
statusResponse.getProgress().getPercentage() + "%)");
}
if ("completed".equals(status)) {
System.out.println("Video generation completed!");
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
```
## Authentication
All clients support Clerk authentication. Set your session token when configuring the client:
### TypeScript
```typescript
const config = new Configuration({
accessToken: 'your-clerk-session-token'
});
```
### Python
```python
configuration.access_token = 'your-clerk-session-token'
```
### Java
```java
client.setAccessToken("your-clerk-session-token");
```
## Error Handling
All clients provide structured error handling:
### TypeScript
```typescript
try {
const response = await api.createVideoGenerationJob(request);
} catch (error) {
if (error.status === 422) {
console.error('Validation error:', error.body);
} else if (error.status === 429) {
console.error('Rate limit exceeded');
} else {
console.error('API error:', error);
}
}
```
### Python
```python
from video_api_client.exceptions import ApiException
try:
response = api.create_video_generation_job(request)
except ApiException as e:
if e.status == 422:
print(f"Validation error: {e.body}")
elif e.status == 429:
print("Rate limit exceeded")
else:
print(f"API error: {e}")
```
## Testing Generated Clients
Use the provided testing script to validate generated clients:
```bash
# Test all generated clients
python scripts/test_clients.py
# Test with custom API URL
python scripts/test_clients.py --api-url https://api.example.com
# Save test results
python scripts/test_clients.py --output-file test_results.json
# Verbose output
python scripts/test_clients.py --verbose
```
The test script validates:
- Client structure and files
- Build/compilation success
- Import/usage capability
- API connectivity
- Basic functionality
## Customization
### Custom Templates
Create custom templates in the `templates/` directory:
```
templates/
βββ typescript/
β βββ api.mustache
β βββ model.mustache
β βββ README.mustache
βββ python/
β βββ api.mustache
β βββ model.mustache
βββ ...
```
### Configuration File
Modify `openapi-generator-config.yaml` to customize generation:
```yaml
typescript:
generatorName: typescript-fetch
additionalProperties:
npmName: my-custom-client
supportsES6: true
withInterfaces: true
```
### Custom Properties
Pass additional properties during generation:
```bash
openapi-generator-cli generate \
-i openapi.json \
-g typescript-fetch \
-o clients/typescript \
--additional-properties=npmName=my-client,supportsES6=true
```
## Publishing Clients
### NPM (TypeScript/JavaScript)
```bash
cd clients/typescript
npm publish
```
### PyPI (Python)
```bash
cd clients/python
python setup.py sdist bdist_wheel
twine upload dist/*
```
### Maven Central (Java)
```bash
cd clients/java
mvn deploy
```
### NuGet (C#)
```bash
cd clients/csharp
dotnet pack
dotnet nuget push *.nupkg
```
## Troubleshooting
### Common Issues
1. **OpenAPI Generator not found**
```bash
npm install -g @openapitools/openapi-generator-cli
```
2. **API server not running**
```bash
# Start the API server first
python -m uvicorn src.app.main:app --reload
```
3. **Build failures**
- Check language-specific requirements
- Verify generated code syntax
- Review error messages in build logs
4. **Import errors**
- Ensure proper installation
- Check Python path and virtual environments
- Verify package structure
### Debug Mode
Enable debug output for troubleshooting:
```bash
# Python script
python scripts/generate_clients.py --verbose
# OpenAPI Generator
openapi-generator-cli generate \
--verbose \
--debug-operations \
-i openapi.json \
-g typescript-fetch \
-o clients/typescript
```
### Validation
Validate OpenAPI specification before generation:
```bash
# Using OpenAPI Generator
openapi-generator-cli validate -i openapi.json
# Using Swagger Editor online
# Visit: https://editor.swagger.io/
```
## Best Practices
1. **Version Management**
- Tag client versions with API versions
- Maintain backward compatibility
- Document breaking changes
2. **Testing**
- Test clients against real API
- Include integration tests
- Validate error handling
3. **Documentation**
- Include usage examples
- Document authentication setup
- Provide troubleshooting guides
4. **Distribution**
- Use semantic versioning
- Publish to appropriate package managers
- Maintain changelogs
## Support
For issues with client generation:
- Check the [OpenAPI Generator documentation](https://openapi-generator.tech/)
- Review API documentation at `/docs`
- Contact support at support@example.com
- File issues on GitHub
## Contributing
To contribute to client generation:
1. Fork the repository
2. Create custom templates or improve scripts
3. Test with multiple languages
4. Submit pull request with documentation
## License
Generated clients inherit the same license as the API project (MIT License). |