### Batch File Upload Example Source: https://docs.kie.ai/file-upload-api/quickstart Demonstrates how to upload multiple local files in a batch. Ensure you have the 'requests' and 'os' libraries installed. Replace 'YOUR_API_KEY' with your actual API key. ```python import requests import os from typing import Optional class FileUploadAPI: def __init__(self, api_key: str, base_url: str = 'https://api.example.com'): self.api_key = api_key self.base_url = base_url self.headers = {'Authorization': f'Bearer {self.api_key}'} def upload_file(self, file_path: str, upload_path: str = '', file_name: Optional[str] = None) -> dict: """Local file upload""" if file_name is None: file_name = os.path.basename(file_path) with open(file_path, 'rb') as f: files = {'file': (file_name, f)} data = {'uploadPath': upload_path} response = requests.post( f'{self.base_url}/api/file-upload', headers=self.headers, files=files, data=data ) if not response.ok: raise Exception(f'Upload failed: {response.text}') return response.json() def upload_from_url(self, file_url: str, upload_path: str = '', file_name: Optional[str] = None) -> dict: """URL file upload""" payload = { 'fileUrl': file_url, 'uploadPath': upload_path, 'fileName': file_name } response = requests.post( f'{self.base_url}/api/file-url-upload', headers={**self.headers, 'Content-Type': 'application/json'}, json=payload ) if not response.ok: raise Exception(f'Upload failed: {response.text}') return response.json() def upload_base64(self, base64_data: str, upload_path: str = '', file_name: Optional[str] = None) -> dict: """Base64 file upload""" payload = { 'base64Data': base64_data, 'uploadPath': upload_path, 'fileName': file_name } response = requests.post( f'{self.base_url}/api/file-base64-upload', headers={**self.headers, 'Content-Type': 'application/json'}, json=payload ) if not response.ok: raise Exception(f'Upload failed: {response.text}') return response.json() # Usage example def main(): uploader = FileUploadAPI('YOUR_API_KEY') # Batch upload local files file_paths = [ '/path/to/file1.jpg', '/path/to/file2.png', '/path/to/document.pdf' ] print("Starting batch file upload...") for i, file_path in enumerate(file_paths): try: result = uploader.upload_file( file_path, 'user-uploads', f'file-{i + 1}-{os.path.basename(file_path)}' ) print(f"File {i + 1} upload successful: {result['data']['fileUrl']}") except Exception as e: print(f"File {i + 1} upload failed: {e}") # Batch upload from URLs urls = [ 'https://example.com/image1.jpg', 'https://example.com/image2.png' ] print("\nStarting batch URL upload...") for i, url in enumerate(urls): try: result = uploader.upload_from_url( url, 'downloads', f'download-{i + 1}.jpg' ) print(f"URL {i + 1} upload successful: {result['data']['fileUrl']}") except Exception as e: print(f"URL {i + 1} upload failed: {e}") if __name__ == '__main__': main() ``` -------------------------------- ### Complete Workflow Example Source: https://docs.kie.ai/runway-api/quickstart This example demonstrates a full workflow: generating a video, waiting for its completion, and then extending it. ```APIDOC ## Complete Workflow Example ### Description This example shows how to use the `RunwayAPI` class to perform a complete video generation workflow, including generation, waiting for completion, and extending the video. ### Usage ```javascript // Assuming RunwayAPI class is defined as above async function main() { const api = new RunwayAPI('YOUR_API_KEY'); try { // Text-to-video generation console.log('Starting video generation...'); const taskId = await api.generateVideo({ prompt: 'A fluffy orange kitten dancing energetically in a colorful room with disco lights', duration: 5, quality: '720p', aspectRatio: '16:9', waterMark: '' }); // Wait for completion console.log(`Task ID: ${taskId}. Waiting for completion...`); const result = await api.waitForCompletion(taskId); console.log('Video generation successful!'); console.log('Video URL:', result.videoInfo.videoUrl); console.log('Thumbnail URL:', result.videoInfo.imageUrl); // Extend video console.log('\nStarting video extension...'); const extendTaskId = await api.extendVideo(taskId, 'The kitten spins, with increasing energy and excitement', '720p'); const extendResult = await api.waitForCompletion(extendTaskId); console.log('Video extension successful!'); console.log('Extended video URL:', extendResult.videoInfo.videoUrl); } catch (error) { console.error('Error:', error.message); } } main(); ``` ### Notes - Replace `'YOUR_API_KEY'` with your actual Runway API key. - The `waitForCompletion` method includes a default timeout to prevent indefinite waiting. ``` -------------------------------- ### Complete Workflow Example Source: https://docs.kie.ai/runway-api/quickstart A comprehensive example demonstrating the usage of the RunwayAPI class to generate a video, wait for its completion, and then extend it. ```APIDOC ## Complete Workflow Example This example demonstrates a full workflow using the `RunwayAPI` class: 1. **Initialize API**: Create an instance of `RunwayAPI` with your API key. 2. **Generate Video**: Call `generate_video` with desired parameters (prompt, duration, quality, etc.). 3. **Wait for Completion**: Use `wait_for_completion` to monitor the generation task. 4. **Retrieve Results**: Access video and thumbnail URLs from the completed task status. 5. **Extend Video**: Call `extend_video` to add more content to the generated video. 6. **Wait for Extension**: Use `wait_for_completion` again for the extension task. 7. **Retrieve Extended Video**: Access the URL of the extended video. ### Usage ```python import requests import time class RunwayAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = 'https://api.kie.ai/api/v1/runway' self.headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } def generate_video(self, **options): response = requests.post(f'{self.base_url}/generate', headers=self.headers, json=options) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Generation failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] def wait_for_completion(self, task_id, max_wait_time=600): start_time = time.time() while time.time() - start_time < max_wait_time: status = self.get_task_status(task_id) state = status['state'] if state == 'wait': print("Task waiting, continue waiting...") elif state == 'queueing': print("Task queuing, continue waiting...") elif state == 'generating': print("Task generating, continue waiting...") elif state == 'success': print("Generation completed successfully!") return status elif state == 'fail': error = status.get('failMsg', 'Task generation failed') print(f"Task generation failed: {error}") raise Exception(error) else: print(f"Unknown status: {state}") if status.get('failMsg'): print(f"Error message: {status['failMsg']}") time.sleep(30) # Wait 30 seconds raise Exception('Generation timeout') def get_task_status(self, task_id): response = requests.get(f'{self.base_url}/record-detail?taskId={task_id}', headers={'Authorization': f'Bearer {self.api_key}'}) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Failed to query status: {result.get('msg', 'Unknown error')}") return result['data'] def extend_video(self, task_id, prompt, quality='720p'): data = { 'taskId': task_id, 'prompt': prompt, 'quality': quality } response = requests.post(f'{self.base_url}/extend', headers=self.headers, json=data) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Extension failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] # Usage Example def main(): api = RunwayAPI('YOUR_API_KEY') try: # Text-to-video generation print('Starting video generation...') task_id = api.generate_video( prompt='A fluffy orange kitten dancing energetically in a colorful room with disco lights', duration=5, quality='720p', aspectRatio='16:9', waterMark='' ) # Wait for completion print(f'Task ID: {task_id}. Waiting for completion...') result = api.wait_for_completion(task_id) print('Video generation successful!') print(f'Video URL: {result["videoInfo"]["videoUrl"]}') print(f'Thumbnail URL: {result["videoInfo"]["imageUrl"]}') # Extend video print('\nStarting video extension...') extend_task_id = api.extend_video(task_id, 'The kitten spins, with increasing energy and excitement', '720p') extend_result = api.wait_for_completion(extend_task_id) print('Video extension successful!') print(f'Extended video URL: {extend_result["videoInfo"]["videoUrl"]}') except Exception as error: print(f'Error: {error}') if __name__ == '__main__': main() ``` ``` -------------------------------- ### Callback Request Examples Source: https://docs.kie.ai/suno-api/upload-and-cover-audio-callbacks Examples of POST requests sent to the `callBackUrl` for different audio generation task statuses. ```APIDOC ## POST /callbackUrl ### Description This endpoint receives POST requests from the Suno API to notify about the status of audio generation tasks. ### Method POST ### Endpoint `callBackUrl` (provided during task submission) ### Headers - **Content-Type**: application/json ### Request Body #### Complete Success Callback ```json { "code": 200, "msg": "All generated successfully.", "data": { "callbackType": "complete", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "source_audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "source_stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "source_image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 198.44 } ] } } ``` #### First Track Complete Callback ```json { "code": 200, "msg": "First track generated successfully.", "data": { "callbackType": "first", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "source_audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "source_stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "source_image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright", "model_name": "chirp-v3-5", "title": "Iron Man", "tags": "electrifying, rock", "createTime": "2025-01-01 00:00:00", "duration": 198.44 } ] } } ``` #### Text Generation Complete Callback ```json { "code": 200, "msg": "Text generation completed.", "data": { "callbackType": "text", "task_id": "2fac****9f72", "data": [] } } ``` #### Failure Callback ```json { "code": 501, "msg": "Audio generation failed.", "data": { "callbackType": "error", "task_id": "2fac****9f72", "data": [] } } ``` ### Response This endpoint is designed to receive callbacks and does not typically return a response to the API. The server should acknowledge receipt of the callback. ### Timeout 15 seconds ``` -------------------------------- ### Generate Music Request Example Source: https://docs.kie.ai/suno-api/generate-music This example demonstrates a comprehensive request to the music generation endpoint, including various optional parameters for customization. ```json { "prompt": "A calm and relaxing piano track with soft melodies", "customMode": true, "instrumental": true, "model": "V4", "callBackUrl": "https://api.example.com/callback", "style": "Classical", "title": "Peaceful Piano Meditation", "negativeTags": "Heavy Metal, Upbeat Drums", "vocalGender": "m", "styleWeight": 0.65, "weirdnessConstraint": 0.65, "audioWeight": 0.65, "personaId": "persona_123", "personaModel": "style_persona" } ``` -------------------------------- ### Audio Generation Callback Example Source: https://docs.kie.ai/suno-api/add-vocals Callback example triggered upon completion of vocal generation, providing task status and generated audio details. ```json { "code": 200, "msg": "All generated successfully.", "data": { "callbackType": "complete", "task_id": "2fac****9f72", "data": [ { "id": "e231****-****-****-****-****8cadc7dc", "audio_url": "https://example.cn/****.mp3", "stream_audio_url": "https://example.cn/****", "image_url": "https://example.cn/****.jpeg", "prompt": "[Verse] Night city lights shining bright" } ] } } ``` -------------------------------- ### JSON Schema Response Format Example Source: https://docs.kie.ai/market/gemini/gemini-2-5-pro This example demonstrates how to configure the `response_format` to expect JSON output adhering to a specified schema. ```json { "response_format": { "type": "json_schema", "properties": { "response": { "type": "string" } } } } ``` -------------------------------- ### API Response Example (Success) Source: https://docs.kie.ai/suno-api/add-vocals Example of a successful API response, including task ID for tracking. ```json { "code": 200, "msg": "Success", "data": { "taskId": "5c79****be8e" } } ``` -------------------------------- ### Gemini API Request Example with Image and Tools Source: https://docs.kie.ai/market/gemini/gemini-2-5-flash An example request demonstrating the use of text and image content, Google Search tool, streaming, and including thoughts. ```json { "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": ">- https://file.aiquickdraw.com/custom-page/akr/section-images/1759055072437dqlsclj2.png" } } ] } ], "tools": [ { "type": "function", "function": { "name": "googleSearch" } } ], "stream": true, "include_thoughts": true, "response_format": { "type": "json_schema", "json_schema": { "name": "structured_output", "strict": true, "schema": } } } ``` -------------------------------- ### Kling v2.1 Standard API Request Example Source: https://docs.kie.ai/market/kling/v2-1-standard This example demonstrates how to structure a request to the Kling v2.1 Standard API for video generation. Ensure all required fields are populated correctly. ```json { "model": "kling/v2-1-standard", "callBackUrl": "https://your-domain.com/api/callback", "input": { "prompt": ">-\n Begin with the uploaded image as the first frame. Gradually\n animate the scene: steam rises and drifts upward from the\n train; lantern lights flicker subtly; cloaked figures begin to\n move slowly — walking, turning, adjusting their belongings. \n Floating dust or magical particles catch the light. The text\n \"KLING 2.1 STANDARD API — Now on Kie.ai\" softly pulses with a\n golden glow. The camera pushes forward slightly, then slowly\n fades to black.", "image_url": ">-\n https://file.aiquickdraw.com/custom-page/akr/section-images/1755256596169mkkwr2ag.png", "duration": "5", "negative_prompt": "blur, distort, and low quality", "cfg_scale": 0.5 } } ``` -------------------------------- ### Convert to WAV Format Request Example Source: https://docs.kie.ai/suno-api/convert-to-wav This example demonstrates the JSON payload required to convert a music track to WAV format. Ensure you provide valid `taskId`, `audioId`, and `callBackUrl`. ```json { "taskId": "5c79****be8e", "audioId": "e231****-****-****-****-****8cadc7dc", "callBackUrl": "https://api.example.com/callback" } ``` -------------------------------- ### Get Timestamped Lyrics Request Example Source: https://docs.kie.ai/suno-api/get-timestamped-lyrics This example demonstrates how to structure a request to the get-timestamped-lyrics endpoint. Ensure you provide valid taskId and audioId obtained from previous music generation tasks. ```json { "taskId": "5c79****be8e", "audioId": "e231****-****-****-****-****8cadc7dc" } ``` -------------------------------- ### Complete Workflow Example: Generate and Wait for Video Source: https://docs.kie.ai/runway-api/quickstart Demonstrates a full workflow including video generation, waiting for completion, and extending the video. Requires an API key and handles potential errors during the process. ```javascript class RunwayAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api.kie.ai/api/v1/runway'; } async generateVideo(options) { const response = await fetch(`${this.baseUrl}/generate`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify(options) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Generation failed: ${result.msg || 'Unknown error'}`); } return result.data.taskId; } async waitForCompletion(taskId, maxWaitTime = 600000) { // Maximum wait 10 minutes const startTime = Date.now(); while (Date.now() - startTime < maxWaitTime) { const status = await this.getTaskStatus(taskId); switch (status.state) { case 'wait': console.log('Task waiting, continue waiting...'); break; case 'queueing': console.log('Task queuing, continue waiting...'); break; case 'generating': console.log('Task generating, continue waiting...'); break; case 'success': console.log('Generation completed successfully!'); return status; case 'fail': const error = status.failMsg || 'Task generation failed'; console.error('Task generation failed:', error); throw new Error(error); default: console.log(`Unknown status: ${status.state}`); if (status.failMsg) { console.error('Error message:', status.failMsg); } break; } // Wait 30 seconds before checking again await new Promise(resolve => setTimeout(resolve, 30000)); } throw new Error('Generation timeout'); } async getTaskStatus(taskId) { const response = await fetch(`${this.baseUrl}/record-detail?taskId=${taskId}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Failed to query status: ${result.msg || 'Unknown error'}`); } return result.data; } async extendVideo(taskId, prompt, quality = '720p') { const response = await fetch(`${this.baseUrl}/extend`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ taskId, prompt, quality }) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Extension failed: ${result.msg || 'Unknown error'}`); } return result.data.taskId; } } // Usage Example async function main() { const api = new RunwayAPI('YOUR_API_KEY'); try { // Text-to-video generation console.log('Starting video generation...'); const taskId = await api.generateVideo({ prompt: 'A fluffy orange kitten dancing energetically in a colorful room with disco lights', duration: 5, quality: '720p', aspectRatio: '16:9', waterMark: '' }); // Wait for completion console.log(`Task ID: ${taskId}. Waiting for completion...`); const result = await api.waitForCompletion(taskId); console.log('Video generation successful!'); console.log('Video URL:', result.videoInfo.videoUrl); console.log('Thumbnail URL:', result.videoInfo.imageUrl); // Extend video console.log('\nStarting video extension...'); const extendTaskId = await api.extendVideo(taskId, 'The kitten spins, with increasing energy and excitement', '720p'); const extendResult = await api.waitForCompletion(extendTaskId); console.log('Video extension successful!'); console.log('Extended video URL:', extendResult.videoInfo.videoUrl); } catch (error) { console.error('Error:', error.message); } } main(); ``` -------------------------------- ### Get HD Video Source: https://docs.kie.ai/veo3-api/quickstart This section explains how to retrieve a 1080P high-definition version of a generated video if a 16:9 aspect ratio was used. It includes examples for Node.js, Python, and cURL. ```APIDOC ## Get HD Video (Optional) If you use 16:9 aspect ratio to generate videos, you can get the 1080P high-definition version: ### Node.js Example ```javascript async function get1080pVideo(taskId) { try { const response = await fetch(`https://api.kie.ai/api/v1/veo/get-1080p-video?taskId=${taskId}`, { method: 'GET', headers: { 'Authorization': 'Bearer YOUR_API_KEY' } }); const data = await response.json(); if (response.ok && data.code === 200) { console.log('1080P video:', data); return data; } } catch (error) { console.error('Failed to get 1080P video:', error.message); return null; } } ``` ### Python Example ```python import requests def get_1080p_video(task_id): url = f"https://api.kie.ai/api/v1/veo/get-1080p-video?taskId={task_id}" headers = {"Authorization": "Bearer YOUR_API_KEY"} try: response = requests.get(url, headers=headers) result = response.json() if response.ok and result.get('code') == 200: print(f"1080P video: {result}") return result except requests.exceptions.RequestException as e: print(f"Failed to get 1080P video: {e}") return None ``` ### cURL Example ```bash curl -X GET "https://api.kie.ai/api/v1/veo/get-1080p-video?taskId=YOUR_TASK_ID" \ -H "Authorization: Bearer YOUR_API_KEY" ``` **Note**: 1080P video requires additional processing time. It's recommended to wait a few minutes after the original video generation is completed before calling this endpoint. ``` -------------------------------- ### Async Music Generation with Callbacks Source: https://docs.kie.ai/suno-api/quickstart Initiate music generation asynchronously and receive notifications via a webhook callback URL upon completion. This example shows how to set up the callback and handle the incoming data. ```javascript const taskId = await api.generateMusic('Upbeat electronic dance music', { customMode: false, instrumental: true, model: 'V4_5', callBackUrl: 'https://your-server.com/suno-callback' }); // Your callback endpoint will receive: app.post('/suno-callback', (req, res) => { const { code, data } = req.body; if (code === 200 && data.callbackType === 'complete') { console.log('Music ready:', data.data); data.data.forEach(track => { console.log('Track:', track.audio_url); }); } res.status(200).json({ status: 'received' }); }); ``` -------------------------------- ### Install Claude Code on Mac Source: https://docs.kie.ai/2151374m0 Use this command to install Claude Code on macOS. Ensure you have curl installed. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` -------------------------------- ### Configure Proxy for Windows Installation Source: https://docs.kie.ai/2151374m0 If the installation fails with ECONNREFUSED, set HTTP and HTTPS proxy environment variables before running the installation script. ```powershell $env:HTTP_PROXY="http://127.0.0.1:`你的端口号` $env:HTTPS_PROXY="http://127.0.0.1:`你的端口号` irm https://claude.ai/install.ps1 | iex ``` -------------------------------- ### Complete Workflow Example with Image Download Source: https://docs.kie.ai/flux-kontext-api/quickstart This snippet demonstrates a complete workflow including image downloading and error handling. It requires the 'requests' library. ```python import requests def download_image(url, filename): response = requests.get(url) response.raise_for_status() with open(filename, 'wb') as f: f.write(response.content) print(f'Downloaded: {filename}') def main(): try: # Assuming edit_result is defined elsewhere and contains 'resultImageUrl' # For demonstration, let's mock it: edit_result = {'resultImageUrl': 'http://example.com/image.jpg'} download_image(edit_result['resultImageUrl'], 'edited_image.jpg') except Exception as error: print(f'Error: {error}') if __name__ == '__main__': main() ``` -------------------------------- ### Success Response Example Source: https://docs.kie.ai/market/codex/gpt-codex An example of a successful response payload from the GPT Codex API. ```APIDOC ## Success Response Example ### Response Body ```json { "output": [ { "type": "reasoning", "id": "rs_xxx", "summary": [] }, { "type": "message", "role": "assistant", "id": "msg_xxx", "content": [ { "type": "output_text", "text": "Hello! How can I help you today?" } ], "status": "completed" } ], "usage": { "total_tokens": 4490, "output_tokens": 47, "input_tokens": 4443 }, "credits_consumed": 0.48, "status": "completed" } ``` ``` -------------------------------- ### Get Cover Generation Details Source: https://docs.kie.ai/llms.txt Get detailed information about Cover generation tasks. ```APIDOC ## Get Cover Generation Details ### Description Get detailed information about Cover generation tasks. ### Method GET ### Endpoint /suno-api/get-cover-suno-details ### Parameters #### Query Parameters - **cover_task_id** (string) - Required - The ID of the cover generation task. ``` -------------------------------- ### Generate and Extend Music with Suno API (JavaScript) Source: https://docs.kie.ai/suno-api/quickstart This example shows how to generate music with specific parameters, wait for completion, and then extend the generated track. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```javascript class SunoAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api.kie.ai/api/v1'; } async generateMusic(prompt, options = {}) { const response = await fetch(`${this.baseUrl}/generate`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, ...options }) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Status check failed: ${result.msg || 'Unknown error'}`); } return result.data; } async waitForCompletion(taskId, interval = 5000) { while (true) { const response = await fetch(`${this.baseUrl}/status/${taskId}`, { method: 'GET', headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Status check failed: ${result.msg || 'Unknown error'}`); } if (result.data.status === 'completed') { return result.data; } await new Promise(resolve => setTimeout(resolve, interval)); } } async extendMusic(audioId, options = {}) { const response = await fetch(`${this.baseUrl}/generate/extend`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ audioId, ...options }) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Status check failed: ${result.msg || 'Unknown error'}`); } return result.data; } } // Usage Example async function main() { const api = new SunoAPI('YOUR_API_KEY'); try { // Generate music with lyrics console.log('Starting music generation...'); const taskId = await api.generateMusic( 'A nostalgic folk song about childhood memories', { customMode: true, instrumental: false, model: 'V4_5', style: 'Folk, Acoustic, Nostalgic', title: 'Childhood Dreams' } ); // Wait for completion console.log(`Task ID: ${taskId}. Waiting for completion...`); const result = await api.waitForCompletion(taskId); console.log('Music generated successfully!'); console.log('Generated tracks:'); result.sunoData.forEach((track, index) => { console.log(`Track ${index + 1}:`); console.log(` Title: ${track.title}`); console.log(` Audio URL: ${track.audioUrl}`); console.log(` Duration: ${track.duration}s`); console.log(` Tags: ${track.tags}`); }); // Extend the first track const firstTrack = result.sunoData[0]; console.log('\nExtending the first track...'); const extendTaskId = await api.extendMusic(firstTrack.id, { defaultParamFlag: true, prompt: 'Continue with a hopeful chorus', style: 'Folk, Uplifting', title: 'Childhood Dreams Extended', continueAt: 60, model: 'V4_5' }); const extendResult = await api.waitForCompletion(extendTaskId); console.log('Music extended successfully!'); console.log('Extended track URL:', extendResult.sunoData[0].audioUrl); } catch (error) { console.error('Error:', error.message); } } main(); ``` -------------------------------- ### Complete Workflow Example for 4o Image API Source: https://docs.kie.ai/4o-image-api/quickstart Demonstrates a full cycle of image generation, waiting for completion, and image editing using the 4o Image API. Requires an API key and includes error handling. ```javascript class FourOImageAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api.kie.ai/api/v1/gpt4o-image'; } async generateImage(options) { const response = await fetch(`${this.baseUrl}/generate`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify(options) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Generation failed: ${result.msg || 'Unknown error'}`); } return result.data.taskId; } async waitForCompletion(taskId, maxWaitTime = 300000) { // 5 minutes max const startTime = Date.now(); while (Date.now() - startTime < maxWaitTime) { const status = await this.getTaskStatus(taskId); switch (status.successFlag) { case 1: console.log('Generation completed successfully!'); return status.response; case 0: console.log('Still generating...'); if (status.progress) { console.log(`Progress: ${(parseFloat(status.progress) * 100).toFixed(1)}%`); } break; case 2: const errorMsg = status.errorMessage || 'Generation failed'; console.error('Error message:', errorMsg); throw new Error(errorMsg); default: console.log('Unknown status:', status.successFlag); if (status.errorMessage) { console.error('Error message:', status.errorMessage); } break; } // Wait 10 seconds before next check await new Promise(resolve => setTimeout(resolve, 10000)); } throw new Error('Generation timeout'); } async getTaskStatus(taskId) { const response = await fetch(`${this.baseUrl}/record-info?taskId=${taskId}`, { headers: { 'Authorization': `Bearer ${this.apiKey}` } }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Status check failed: ${result.msg || 'Unknown error'}`); } return result.data; } async getDownloadUrl(imageUrl) { const response = await fetch(`${this.baseUrl}/download-url`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ imageUrl }) }); const result = await response.json(); if (!response.ok || result.code !== 200) { throw new Error(`Get download URL failed: ${result.msg || 'Unknown error'}`); } return result.data.downloadUrl; } } // Usage Example async function main() { const api = new FourOImageAPI('YOUR_API_KEY'); try { // Text-to-Image Generation console.log('Starting image generation...'); const taskId = await api.generateImage({ prompt: 'A futuristic cityscape with flying cars and neon lights, cyberpunk style', size: '1:1', nVariants: 2, isEnhance: true, enableFallback: true }); // Wait for completion console.log(`Task ID: ${taskId}. Waiting for completion...`); const result = await api.waitForCompletion(taskId); console.log('Image generation successful!'); result.result_urls.forEach((url, index) => { console.log(`Image ${index + 1}: ${url}`); }); // Get download URL const downloadUrl = await api.getDownloadUrl(result.result_urls[0]); console.log('Download URL:', downloadUrl); // Image Editing Example console.log('\nStarting image editing...'); const editTaskId = await api.generateImage({ filesUrl: [result.result_urls[0]], prompt: 'Add beautiful rainbow in the sky', size: '3:2' }); const editResult = await api.waitForCompletion(editTaskId); console.log('Image editing successful!'); console.log('Edited image:', editResult.result_urls[0]); } catch (error) { console.error('Error:', error.message); } } main(); ``` -------------------------------- ### Install Claude Code on Windows Source: https://docs.kie.ai/2151374m0 Use this PowerShell command to install Claude Code on Windows. Ensure you have internet access. ```powershell irm https://claude.ai/install.ps1 | iex ``` -------------------------------- ### File Stream Upload Example Command Source: https://docs.kie.ai/file-upload-api/upload-file-stream Use this command to upload a file via a binary stream. Ensure you replace YOUR_API_KEY with your actual API key and adjust the file path and optional uploadPath/fileName as needed. Files are temporary and deleted after 3 days. ```bash curl -X POST https://kieai.redpandaai.co/api/file-stream-upload \ -H "Authorization: Bearer YOUR_API_KEY" \ -F "file=@/path/to/your-file.jpg" \ -F "uploadPath=images/user-uploads" \ -F "fileName=custom-name.jpg" ``` -------------------------------- ### Python Runway API Client and Workflow Example Source: https://docs.kie.ai/runway-api/quickstart This Python script demonstrates a complete workflow for interacting with the Runway API. It includes a client class for managing API calls and a main function to showcase video generation, status checking, and video extension. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```python import requests import time class RunwayAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = 'https://api.kie.ai/api/v1/runway' self.headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } def generate_video(self, **options): response = requests.post(f'{self.base_url}/generate', headers=self.headers, json=options) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Generation failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] def wait_for_completion(self, task_id, max_wait_time=600): start_time = time.time() while time.time() - start_time < max_wait_time: status = self.get_task_status(task_id) state = status['state'] if state == 'wait': print("Task waiting, continue waiting...") elif state == 'queueing': print("Task queuing, continue waiting...") elif state == 'generating': print("Task generating, continue waiting...") elif state == 'success': print("Generation completed successfully!") return status elif state == 'fail': error = status.get('failMsg', 'Task generation failed') print(f"Task generation failed: {error}") raise Exception(error) else: print(f"Unknown status: {state}") if status.get('failMsg'): print(f"Error message: {status['failMsg']}") time.sleep(30) # Wait 30 seconds raise Exception('Generation timeout') def get_task_status(self, task_id): response = requests.get(f'{self.base_url}/record-detail?taskId={task_id}', headers={'Authorization': f'Bearer {self.api_key}'}) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Failed to query status: {result.get('msg', 'Unknown error')}") return result['data'] def extend_video(self, task_id, prompt, quality='720p'): data = { 'taskId': task_id, 'prompt': prompt, 'quality': quality } response = requests.post(f'{self.base_url}/extend', headers=self.headers, json=data) result = response.json() if not response.ok or result.get('code') != 200: raise Exception(f"Extension failed: {result.get('msg', 'Unknown error')}") return result['data']['taskId'] # Usage Example def main(): api = RunwayAPI('YOUR_API_KEY') try: # Text-to-video generation print('Starting video generation...') task_id = api.generate_video( prompt='A fluffy orange kitten dancing energetically in a colorful room with disco lights', duration=5, quality='720p', aspectRatio='16:9', waterMark='' ) # Wait for completion print(f'Task ID: {task_id}. Waiting for completion...') result = api.wait_for_completion(task_id) print('Video generation successful!') print(f'Video URL: {result["videoInfo"]["videoUrl"]}') print(f'Thumbnail URL: {result["videoInfo"]["imageUrl"]}') # Extend video print('\nStarting video extension...') extend_task_id = api.extend_video(task_id, 'The kitten spins, with increasing energy and excitement', '720p') extend_result = api.wait_for_completion(extend_task_id) print('Video extension successful!') print(f'Extended video URL: {extend_result["videoInfo"]["videoUrl"]}') except Exception as error: print(f'Error: {error}') if __name__ == '__main__': main() ``` -------------------------------- ### Usage Example Source: https://docs.kie.ai/flux-kontext-api/quickstart Demonstrates how to use the FluxKontextAPI class to generate an image, wait for its completion, and then edit it. ```APIDOC ## Usage Example This example shows how to instantiate the `FluxKontextAPI` and perform text-to-image generation followed by image editing. ```javascript async function main() { const api = new FluxKontextAPI('YOUR_API_KEY'); try { // Text-to-Image Generation console.log('Starting image generation...'); const taskId = await api.generateImage( 'A futuristic cityscape at night with neon lights and flying cars', { aspectRatio: '16:9', model: 'flux-kontext-max', promptUpsampling: true } ); // Wait for completion console.log(`Task ID: ${taskId}. Waiting for completion...`); const result = await api.waitForCompletion(taskId); console.log('Image generated successfully!'); console.log('Result Image URL:', result.resultImageUrl); console.log('Original Image URL (valid 10 min):', result.originImageUrl); // Image Editing Example console.log('\nStarting image editing...'); const editTaskId = await api.editImage( 'Add rainbow in the sky', result.resultImageUrl, { aspectRatio: '16:9' } ); const editResult = await api.waitForCompletion(editTaskId); console.log('Image edited successfully!'); console.log('Edited Image URL:', editResult.resultImageUrl); } catch (error) { console.error('Error:', error.message); } } main(); ``` ``` -------------------------------- ### GPT-5.2 Chat Completion Response Example Source: https://docs.kie.ai/market/chat/gpt-5-2 This is an example of a successful response from the GPT-5.2 chat completions endpoint, including usage statistics. ```json { "id": "chatcmpl-example-123", "object": "chat.completion", "created": 1741569952, "model": "gpt-5-2", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "hello,can i help you?", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 50, "total_tokens": 60 } } ```