Ejemplos de Codigo
Ejemplos completos de como integrar la API de ZUI GEN en diferentes lenguajes de programacion.
cURL
Ejemplo basico usando cURL desde la linea de comandos.
Generar una imagenbash
# Generar imagen TASK_ID=$(curl -s -X POST https://gen.zui.es/api/v1/generate \ -H "Authorization: Bearer $ZUI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "flux/schnell", "prompt": "A futuristic city at night, neon lights, cyberpunk" }' | jq -r '.task_id') echo "Task ID: $TASK_ID" # Esperar y obtener resultado sleep 10 curl -s https://gen.zui.es/api/v1/task/$TASK_ID \ -H "Authorization: Bearer $ZUI_API_KEY" | jq JavaScript / TypeScript
Ejemplo completo con polling para obtener resultados.
zui-gen-client.tstypescript
// Configuracionconst API_BASE = 'https://gen.zui.es/api/v1';const API_KEY = process.env.ZUI_API_KEY!;// Tiposinterface GenerateRequest { model: string; prompt: string; params?: Record<string, string>; image_url?: string;}interface Task { task_id: string; model: string; category: 'image' | 'video' | 'audio'; status: 'processing' | 'completed' | 'failed'; output_urls: string[] | null; error: string | null;}// Generar contenidoasync function generate(request: GenerateRequest): Promise<Task> { const response = await fetch(`${API_BASE}/generate`, { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(request), }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Generation failed'); } return response.json();}// Consultar tareaasync function getTask(taskId: string): Promise<Task> { const response = await fetch(`${API_BASE}/task/${taskId}`, { headers: { 'Authorization': `Bearer ${API_KEY}`, }, }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Failed to get task'); } return response.json();}// Esperar resultado con pollingasync function waitForResult( taskId: string, maxWaitMs = 600000 // 10 minutes): Promise<string[]> { const startTime = Date.now(); let interval = 2000; while (Date.now() - startTime < maxWaitMs) { const task = await getTask(taskId); if (task.status === 'completed' && task.output_urls) { return task.output_urls; } if (task.status === 'failed') { throw new Error(task.error || 'Generation failed'); } await new Promise(r => setTimeout(r, interval)); interval = Math.min(interval * 1.5, 10000); } throw new Error('Task timed out');}// Ejemplo de usoasync function main() { console.log('Generando imagen...'); const task = await generate({ model: 'flux/schnell', prompt: 'A serene mountain landscape at sunrise', params: { aspect_ratio: '16:9' }, }); console.log(`Task creado: ${task.task_id}`); const urls = await waitForResult(task.task_id); console.log('Resultado:', urls[0]);}main().catch(console.error);Python
Ejemplo usando la libreria requests.
zui_gen_client.pypython
import osimport timeimport requestsfrom typing import Optional, List, Dict, Any# ConfiguracionAPI_BASE = "https://gen.zui.es/api/v1"API_KEY = os.environ.get("ZUI_API_KEY")class ZuiGenClient: def __init__(self, api_key: str): self.api_key = api_key self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } def generate( self, model: str, prompt: str, params: Optional[Dict[str, str]] = None, image_url: Optional[str] = None, ) -> Dict[str, Any]: """Crear una nueva tarea de generacion.""" payload = { "model": model, "prompt": prompt, } if params: payload["params"] = params if image_url: payload["image_url"] = image_url response = requests.post( f"{API_BASE}/generate", headers=self.headers, json=payload, ) response.raise_for_status() return response.json() def get_task(self, task_id: str) -> Dict[str, Any]: """Obtener estado de una tarea.""" response = requests.get( f"{API_BASE}/task/{task_id}", headers=self.headers, ) response.raise_for_status() return response.json() def wait_for_result( self, task_id: str, max_wait_seconds: int = 600, ) -> List[str]: """Esperar a que una tarea termine y devolver URLs.""" start_time = time.time() interval = 2 while time.time() - start_time < max_wait_seconds: task = self.get_task(task_id) if task["status"] == "completed": return task["output_urls"] if task["status"] == "failed": raise Exception(task.get("error", "Generation failed")) time.sleep(interval) interval = min(interval * 1.5, 10) raise TimeoutError("Task timed out") def get_me(self) -> Dict[str, Any]: """Obtener info del usuario y creditos.""" response = requests.get( f"{API_BASE}/me", headers=self.headers, ) response.raise_for_status() return response.json() def get_models(self, category: Optional[str] = None) -> Dict[str, Any]: """Listar modelos disponibles.""" params = {} if category: params["category"] = category response = requests.get( f"{API_BASE}/models", headers=self.headers, params=params, ) response.raise_for_status() return response.json()# Ejemplo de usoif __name__ == "__main__": client = ZuiGenClient(API_KEY) # Ver creditos disponibles me = client.get_me() print(f"Creditos: {me['credits']['balance']}") # Generar imagen print("Generando imagen...") task = client.generate( model="flux/schnell", prompt="A magical forest with glowing mushrooms", params={"aspect_ratio": "1:1"}, ) print(f"Task ID: {task['task_id']}") # Esperar resultado urls = client.wait_for_result(task["task_id"]) print(f"Resultado: {urls[0]}")Node.js (Ejemplo Minimo)
Ejemplo simplificado para empezar rapidamente.
quick-start.jsjavascript
const API_KEY = process.env.ZUI_API_KEY;// Generar y esperar resultadoasync function generateImage(prompt) { // 1. Crear tarea const createRes = await fetch('https://gen.zui.es/api/v1/generate', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'flux/schnell', prompt: prompt, }), }); const { task_id } = await createRes.json(); console.log('Task creado:', task_id); // 2. Polling hasta completar while (true) { await new Promise(r => setTimeout(r, 3000)); const statusRes = await fetch( `https://gen.zui.es/api/v1/task/${task_id}`, { headers: { 'Authorization': `Bearer ${API_KEY}` } } ); const task = await statusRes.json(); console.log('Status:', task.status); if (task.status === 'completed') { return task.output_urls[0]; } if (task.status === 'failed') { throw new Error(task.error); } }}// EjecutargenerateImage('A cute robot drinking coffee') .then(url => console.log('Imagen generada:', url)) .catch(err => console.error('Error:', err));PHP
Ejemplo usando cURL nativo de PHP.
zui-gen.phpphp
<?phpclass ZuiGenClient { private string $apiKey; private string $baseUrl = 'https://gen.zui.es/api/v1'; public function __construct(string $apiKey) { $this->apiKey = $apiKey; } private function request(string $method, string $endpoint, ?array $data = null): array { $ch = curl_init(); $url = $this->baseUrl . $endpoint; $headers = [ 'Authorization: Bearer ' . $this->apiKey, 'Content-Type: application/json', ]; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); if ($method === 'POST' && $data) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode >= 400) { throw new Exception("API error: " . $response); } return json_decode($response, true); } public function generate(string $model, string $prompt, array $params = []): array { return $this->request('POST', '/generate', [ 'model' => $model, 'prompt' => $prompt, 'params' => $params, ]); } public function getTask(string $taskId): array { return $this->request('GET', '/task/' . $taskId); } public function waitForResult(string $taskId, int $maxWait = 600): array { $start = time(); $interval = 2; while (time() - $start < $maxWait) { $task = $this->getTask($taskId); if ($task['status'] === 'completed') { return $task['output_urls']; } if ($task['status'] === 'failed') { throw new Exception($task['error'] ?? 'Generation failed'); } sleep($interval); $interval = min($interval * 1.5, 10); } throw new Exception('Task timed out'); }}// Ejemplo de uso$client = new ZuiGenClient(getenv('ZUI_API_KEY'));$task = $client->generate('flux/schnell', 'A space station orbiting Earth');echo "Task ID: " . $task['task_id'] . "\n";$urls = $client->waitForResult($task['task_id']);echo "Result: " . $urls[0] . "\n";Consejos de Integracion
- Siempre almacena la API Key en variables de entorno, nunca en el codigo.
- Implementa manejo de errores robusto para reintentos en caso de fallos temporales.
- Usa webhooks si necesitas notificaciones en lugar de polling constante.
- Descarga y almacena los resultados - las URLs son temporales.
- Consulta
/api/v1/mepara verificar creditos antes de generar.