Skip to main content

api_v1_job_job_id_get()

Get current task status:
use legnext_rust_sdk::{
    apis::configuration::Configuration,
    apis::image_api,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Configuration::new();
    config.base_path = "https://api.legnext.ai".to_string();

    let api_key = "your-api-key-here";
    let job_id = "job-123";

    let task = image_api::api_v1_job_job_id_get(
        &config,
        job_id,
        Some(api_key),
    ).await?;

    println!("Status: {:?}", task.status);
    println!("Progress: {}%", task.progress.unwrap_or(0));

    if task.status == Some("completed".to_string()) {
        println!("Result: {:?}", task.output);
    }

    Ok(())
}

Polling for Completion

Wait for task completion with polling:
use legnext_rust_sdk::{
    apis::configuration::Configuration,
    apis::image_api,
};
use std::time::Duration;
use tokio::time::sleep;

async fn wait_for_completion(
    config: &Configuration,
    job_id: &str,
    api_key: &str,
    timeout_seconds: u64,
    poll_interval_seconds: u64,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    let start_time = std::time::Instant::now();
    let timeout = Duration::from_secs(timeout_seconds);

    loop {
        let task = image_api::api_v1_job_job_id_get(
            config,
            job_id,
            Some(api_key),
        ).await?;

        println!("Current status: {:?}", task.status);

        if task.status == Some("completed".to_string()) {
            println!("Task completed successfully!");
            println!("Output: {:?}", task.output);
            return Ok(task.output.unwrap_or_default());
        } else if task.status == Some("failed".to_string()) {
            return Err(format!("Task failed: {:?}", task.error).into());
        }

        // Check timeout
        if start_time.elapsed() > timeout {
            return Err(format!("Task timeout after {} seconds", timeout_seconds).into());
        }

        // Wait before next poll
        sleep(Duration::from_secs(poll_interval_seconds)).await;
    }
}
Usage:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Configuration::new();
    config.base_path = "https://api.legnext.ai".to_string();

    let api_key = std::env::var("LEGNEXT_API_KEY")?;
    let job_id = "job-123";

    match wait_for_completion(&config, job_id, &api_key, 300, 3).await {
        Ok(result) => println!("Final result: {:?}", result),
        Err(e) => eprintln!("Error: {}", e),
    }

    Ok(())
}

Complete Example with Error Handling

use legnext_rust_sdk::{
    apis::configuration::Configuration,
    apis::image_api,
};
use std::collections::HashMap;
use std::time::Duration;
use tokio::time::sleep;

async fn wait_for_completion(
    config: &Configuration,
    job_id: &str,
    api_key: &str,
    timeout_seconds: u64,
    poll_interval_seconds: u64,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    let start_time = std::time::Instant::now();
    let timeout = Duration::from_secs(timeout_seconds);

    loop {
        let task = image_api::api_v1_job_job_id_get(
            config,
            job_id,
            Some(api_key),
        ).await?;

        if task.status == Some("completed".to_string()) {
            return Ok(task.output.unwrap_or_default());
        } else if task.status == Some("failed".to_string()) {
            return Err(format!("Task failed: {:?}", task.error).into());
        }

        if start_time.elapsed() > timeout {
            return Err(format!("Task timeout after {} seconds", timeout_seconds).into());
        }

        sleep(Duration::from_secs(poll_interval_seconds)).await;
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Configuration::new();
    config.base_path = "https://api.legnext.ai".to_string();

    let api_key = std::env::var("LEGNEXT_API_KEY")
        .expect("LEGNEXT_API_KEY environment variable not set");

    // Step 1: Start generation
    let mut body = HashMap::new();
    body.insert("text".to_string(), "a beautiful sunset over mountains");

    let response = image_api::api_v1_diffusion_post(
        &config,
        Some(&api_key),
        Some(serde_json::to_value(body)?),
    ).await?;

    let job_id = response.job_id.ok_or("No job_id in response")?;
    println!("Job started: {}", job_id);

    // Step 2: Poll for completion
    let result = wait_for_completion(&config, &job_id, &api_key, 600, 3).await?;

    // Step 3: Get final result
    println!("Image URLs: {:?}", result);

    Ok(())
}

Error Handling

HTTP Error Handling: The Rust SDK returns Result types. Handle errors using pattern matching:
use legnext_rust_sdk::apis::Error;

match image_api::api_v1_diffusion_post(&config, Some(&api_key), Some(body)).await {
    Ok(response) => {
        println!("Success: {:?}", response);
    }
    Err(Error::ResponseError(ref content)) => {
        match content.status {
            400 => eprintln!("Validation error: {:?}", content.content),
            401 => eprintln!("Authentication error: Invalid API key"),
            404 => eprintln!("Resource not found"),
            429 => eprintln!("Rate limit exceeded. Please retry later."),
            500 | 502 | 503 => eprintln!("Server error: {:?}", content.content),
            _ => eprintln!("API error ({}): {:?}", content.status, content.content),
        }
    }
    Err(e) => eprintln!("Unexpected error: {:?}", e),
}
Common HTTP Status Codes:
Status CodeDescriptionAction
400Invalid request parametersCheck request body format
401Invalid API keyVerify API key is correct
404Resource not foundCheck job ID exists
429Rate limit exceededWait and retry with backoff
500/502/503Server errorRetry with exponential backoff
Retry Logic with Exponential Backoff:
use std::time::Duration;
use tokio::time::sleep;

async fn call_with_retry<F, T>(
    api_call: F,
    max_retries: u32,
) -> Result<T, Box<dyn std::error::Error>>
where
    F: Fn() -> futures::future::BoxFuture<'static, Result<T, legnext_rust_sdk::apis::Error>>,
{
    for i in 0..max_retries {
        match api_call().await {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(ref content)) => {
                if content.status == 429 {
                    // Rate limited - wait and retry
                    sleep(Duration::from_secs(5)).await;
                    continue;
                } else if content.status >= 500 {
                    // Server error - exponential backoff
                    let delay = Duration::from_secs(2_u64.pow(i));
                    sleep(delay).await;
                    if i == max_retries - 1 {
                        return Err(Box::new(content.clone()));
                    }
                    continue;
                } else {
                    // Other errors - don't retry
                    return Err(Box::new(content.clone()));
                }
            }
            Err(e) => return Err(Box::new(e)),
        }
    }
    Err("Max retries exceeded".into())
}

// Usage
let result = call_with_retry(
    || Box::pin(image_api::api_v1_diffusion_post(&config, Some(&api_key), Some(body.clone()))),
    3,
).await?;

Concurrent Operations with Tokio

For processing multiple tasks concurrently:
use tokio::try_join;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Configuration::new();
    config.base_path = "https://api.legnext.ai".to_string();

    let api_key = std::env::var("LEGNEXT_API_KEY")?;

    let prompts = vec!["sunset", "mountains", "ocean"];

    // Start all generations concurrently
    let mut handles = vec![];

    for prompt in prompts {
        let config_clone = config.clone();
        let api_key_clone = api_key.clone();
        let prompt_clone = prompt.to_string();

        let handle = tokio::spawn(async move {
            let mut body = HashMap::new();
            body.insert("text".to_string(), prompt_clone.clone());

            let response = image_api::api_v1_diffusion_post(
                &config_clone,
                Some(&api_key_clone),
                Some(serde_json::to_value(body)?),
            ).await?;

            let job_id = response.job_id.ok_or("No job_id")?;

            // Wait for completion
            let result = wait_for_completion(
                &config_clone,
                &job_id,
                &api_key_clone,
                600,
                3,
            ).await?;

            Ok::<_, Box<dyn std::error::Error>>(result)
        });

        handles.push(handle);
    }

    // Wait for all tasks to complete
    for handle in handles {
        match handle.await {
            Ok(Ok(result)) => println!("Image generated: {:?}", result),
            Ok(Err(e)) => eprintln!("Task error: {}", e),
            Err(e) => eprintln!("Join error: {}", e),
        }
    }

    Ok(())
}

Progress Callbacks

use std::sync::Arc;
use tokio::sync::Mutex;

async fn wait_for_completion_with_progress<F>(
    config: &Configuration,
    job_id: &str,
    api_key: &str,
    on_progress: F,
    timeout_seconds: u64,
    poll_interval_seconds: u64,
) -> Result<serde_json::Value, Box<dyn std::error::Error>>
where
    F: Fn(i32, &str),
{
    let start_time = std::time::Instant::now();
    let timeout = Duration::from_secs(timeout_seconds);

    loop {
        let task = image_api::api_v1_job_job_id_get(
            config,
            job_id,
            Some(api_key),
        ).await?;

        // Call progress callback
        on_progress(
            task.progress.unwrap_or(0),
            task.status.as_deref().unwrap_or("unknown"),
        );

        if task.status == Some("completed".to_string()) {
            return Ok(task.output.unwrap_or_default());
        } else if task.status == Some("failed".to_string()) {
            return Err(format!("Task failed: {:?}", task.error).into());
        }

        if start_time.elapsed() > timeout {
            return Err(format!("Task timeout after {} seconds", timeout_seconds).into());
        }

        sleep(Duration::from_secs(poll_interval_seconds)).await;
    }
}

// Usage
let result = wait_for_completion_with_progress(
    &config,
    &job_id,
    &api_key,
    |progress, status| {
        println!("Progress: {}% - Status: {}", progress, status);
    },
    600,
    3,
).await?;

Learn More