windmill_var 0.3.0

A short description of your crate's functionality.
Documentation
use reqwest::header::{HeaderMap, HeaderValue};
use std::env;
use std::error::Error;
use serde::Deserialize; // Add this import

// Define a struct to deserialize the relevant part of the JSON response
#[derive(Deserialize)]
struct VariableResponse {
    value: String, // We only care about the 'value' field
    // If you needed other fields, you would add them here
    // is_secret: bool,
    // description: String,
    // etc.
}

pub async fn get_var(
    variable_path_segment: &str,
) -> Result<String, Box<dyn Error>> {

    let base_url = env::var("BASE_INTERNAL_URL")
        .map_err(|e| format!("Failed to read environment variable 'BASE_INTERNAL_URL': {}", e))?;
    let workspace = env::var("WM_WORKSPACE")
        .map_err(|e| format!("Failed to read environment variable 'WM_WORKSPACE': {}", e))?;
    let token = env::var("WM_TOKEN")
        .map_err(|e| format!("Failed to read environment variable 'WM_TOKEN': {}", e))?;

    let url = format!(
        "{}/api/w/{}/variables/get/{}",
        base_url,
        workspace,
        variable_path_segment
    );

    let mut headers = HeaderMap::new();
    let auth_value = format!("Bearer {}", token);
    headers.insert(
        "Authorization",
        HeaderValue::from_str(&auth_value)
            .map_err(|e| format!("Failed to create Authorization header value: {}", e))?,
    );

    let client = reqwest::Client::new();

    let response = client
        .get(&url)
        .headers(headers)
        .send()
        .await?;

    let status = response.status();

    if status.is_success() {
        // Use reqwest's json() method to deserialize directly into our struct
        let variable_response: VariableResponse = response.json().await?;

        // Return only the value field
        Ok(variable_response.value)
    } else {
         let body = response.text().await?;
         eprintln!("API error response (status: {}): {}", status, body);
        Err(format!("HTTP request failed: status code {}", status).into())
    }
}