### Rust: Example GET Request Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/client.md Example demonstrating how to define a `ListQuery` struct with optional filtering and use the `get` convenience method to list virtual machines. ```rust #[derive(Serialize)] struct ListQuery { #[serde(skip_serializing_if = "Option::is_none")] filter: Option, } let query = ListQuery { filter: None }; let vms: Vec = client.get("/nodes/pve/qemu", &query).await?; ``` -------------------------------- ### Start VM Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Starts a specific virtual machine on a given node. ```APIDOC ## POST /nodes/{node}/qemu/{vmid}/status/start ### Description Starts a virtual machine on the specified node. ### Method POST ### Endpoint /nodes/{node}/qemu/{vmid}/status/start ### Parameters #### Path Parameters - **node** (String) - Required - The name of the node where the VM is located. - **vmid** (Integer) - Required - The ID of the VM to start. #### Request Body (No specific request body fields are documented in the source for this action, but parameters might be required by the underlying API.) ### Request Example (No specific request body example provided in the source.) ### Response #### Success Response (200) (No specific response fields are documented in the source for this action.) #### Response Example (No specific response example provided in the source.) ``` -------------------------------- ### Rust: Example POST Request Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/client.md Example demonstrating how to create a `CreateVmRequest` struct and send a POST request to create a virtual machine using the `post` convenience method. ```rust #[derive(Serialize)] struct CreateVmRequest { vmid: i32, name: String, } let req = CreateVmRequest { vmid: 100, name: "vm-test".to_string() }; let result = client.post("/nodes/pve/qemu", &req).await?; ``` -------------------------------- ### User Management Example Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md This example demonstrates how to initialize the Proxmox API client, authenticate using an API token, retrieve available endpoints, and access user-related functionalities. ```APIDOC ## User Management Example This example demonstrates how to initialize the Proxmox API client, authenticate using an API token, retrieve available endpoints, and access user-related functionalities. ```rust use proxmox_api::ReqwestClient; use proxmox_api::access::AccessClient; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize client with API token let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret-token"); let access = AccessClient::new(http_client); // Get available endpoints let endpoints = access.get().await?; for endpoint in endpoints { println!("Available: {}", endpoint.subdir); } // Access users sub-client let users_client = access.users(); // Further operations... // Check login capability access.ticket().get().await?; println!("API is accessible"); Ok(()) } ``` ``` -------------------------------- ### Start a VM Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Initiates the startup of a specific virtual machine on a given node and then checks its status. Requires the node client and VM ID. Note: 'params' is a placeholder for potential start parameters. ```rust let node_client = nodes.node("pve"); let vmid = 100; // Start the VM node_client.qemu().vmid(vmid).status().start().post(params).await?; // Check status let status = node_client.qemu().vmid(vmid).status().current().get().await?; println!("VM status: {}", status.status); ``` -------------------------------- ### Call Proxmox API Methods Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/README.md Provides examples of calling various HTTP methods (GET, POST, PUT, DELETE) on Proxmox API endpoints, including listing VMs, creating VMs, and starting a specific VM. ```rust // 4. Call methods (get, post, put, delete) // qemu.get() — List VMs // qemu.post(params) — Create VM // qemu.vmid(100).status().start().post() — Start VM ``` -------------------------------- ### Ticket Request Example Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Example of creating a Ticket request and sending it to the /access/ticket endpoint. Requires the 'proxmox_api::client::Client' trait. ```rust use proxmox_api::client::Client; let ticket_req = Ticket::new("root", "pam", "password123"); let response: TicketResponse = client.post("/access/ticket", &ticket_req).await?; ``` -------------------------------- ### Basic Setup with API Token Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/reqwest-client.md Initializes ReqwestClient with a Proxmox API endpoint and an API token for authentication. Requires the `proxmox_api` and `tokio` crates. ```rust use proxmox_api::ReqwestClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("my-token-id", "secret-token-value"); // Client is now ready to use Ok(()) } ``` -------------------------------- ### Check Version Compatibility Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md This example demonstrates how to fetch version information and check if it meets a minimum requirement using Rust. ```APIDOC ## Check Version Compatibility This example demonstrates how to fetch version information and check if it meets a minimum requirement using Rust. ```rust use proxmox_api::ReqwestClient; use proxmox_api::version::VersionClient; #[tokio::main] async fn main() -> Result<(), Box> { let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ); // No need to authenticate for version endpoint let version = VersionClient::new(http_client); let info = version.get().await?; println!("Connected to: {}", info.productname); println!("Version: {}", info.version); println!("Release: {}", info.release); // Check if version meets minimum requirement if version_meets_requirement(&info.version, "8.1.0") { println!("Version is acceptable"); } else { println!("Version is too old"); } Ok(()) } fn version_meets_requirement(version: &str, required: &str) -> bool { let v: Vec = version.split('.').filter_map(|s| s.parse().ok()).collect(); let r: Vec = required.split('.').filter_map(|s| s.parse().ok()).collect(); v.iter().zip(r.iter()).any(|(a, b)| a > b) || (v.get(0) == r.get(0) && v.get(1) == r.get(1) && v.get(2).unwrap_or(&0) >= r.get(2).unwrap_or(&0)) } ``` ``` -------------------------------- ### Display Formatted Version Info Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Example of how to display formatted system information obtained from the version endpoint. ```APIDOC ## Display Formatted Version Info Example of how to display formatted system information obtained from the version endpoint. ```rust let info = version_client.get().await?; println!("╔════════════════════════════════════╗"); println!("║ Proxmox VE System Information ║"); println!("╠════════════════════════════════════╣"); println!("║ Product: {:24}║", info.productname); println!("║ Version: {:24}║", info.version); println!("║ Release: {:24}║", info.release); println!("║ Keyboard: {:24}║", info.keyboard); println!("║ Repository: {:24}║", info.repoid); println!("╚════════════════════════════════════╝"); ``` ``` -------------------------------- ### Pre-authentication System Check Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md This example shows how to check if the Proxmox API is reachable and responsive without requiring authentication. ```APIDOC ## Pre-authentication System Check This example shows how to check if the Proxmox API is reachable and responsive without requiring authentication. ```rust async fn check_api_availability(host: &str) -> Result> { let client = ReqwestClient::new(host, "", "", None); let version = VersionClient::new(client); match version.get().await { Ok(_) => { println!("API is reachable and responsive"); Ok(true) }, Err(_) => { println!("API is unreachable"); Ok(false) } } } ``` ``` -------------------------------- ### Example API Response Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md This is an example of the JSON response format returned by the API version endpoint. ```json { "version": "9.1.2", "release": "bookworm", "keyboard": "en-us", "repoid": "pve-repo", "productname": "Proxmox VE" } ``` -------------------------------- ### Rust: GET Request with Query Parameters Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/client.md Use the `get` convenience method for sending GET requests with serialized query parameters. This method internally uses `request_with_query` with the GET method. ```rust fn get(&self, path: &str, query: &Q) -> impl Future> where Q: Serialize, R: DeserializeOwned; ``` -------------------------------- ### Basic Nodes Client Path Handling Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/path.md Illustrates a simplified generated client for nodes, showing how a base path is initialized and used for GET requests. ```rust // Simplified example from generated code pub struct NodesClient { client: T, path: String, // e.g., "/nodes" } impl NodesClient { pub fn new(client: T) -> Self { Self { client, path: "/nodes".to_string(), } } pub async fn get(&self) -> Result, T::Error> { self.client.get(&self.path, &()).await } } ``` -------------------------------- ### Proxmox API Access Client Example Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md Demonstrates initializing the ReqwestClient with an API token and using the AccessClient to fetch available endpoints, access the users sub-client, and check API accessibility via ticket. ```rust use proxmox_api::ReqwestClient; use proxmox_api::access::AccessClient; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize client with API token let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret-token"); let access = AccessClient::new(http_client); // Get available endpoints let endpoints = access.get().await?; for endpoint in endpoints { println!("Available: {}", endpoint.subdir); } // Access users sub-client let users_client = access.users(); // Further operations... // Check login capability access.ticket().get().await?; println!("API is accessible"); Ok(()) } ``` -------------------------------- ### Ticket Response Usage Example Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Example of processing the TicketResponse to extract and set the authentication ticket and CSRF token. Assumes 'auth_state' has a 'set_csrf' method. ```rust let response: TicketResponse = client.post("/access/ticket", &ticket_request).await?; if let (Some(ticket), Some(csrf)) = (response.auth_ticket, response.csrf_token) { auth_state.set_csrf(ticket, csrf); } ``` -------------------------------- ### UsernameStr Construction Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md Example of constructing a UsernameStr from a String. Ensure the input string meets the length constraints. ```rust let username = UsernameStr::try_from("root".to_string())?; ``` -------------------------------- ### TryFrom &str Conversion for Path Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/path.md Parses a string slice into a Path struct. The path must start with '/' and segments are split by '/'. Returns an error if the path does not start with '/'. ```rust impl TryFrom<&str> for Path ``` ```rust use proxmox_api::Path; use std::convert::TryFrom; let path = Path::try_from("/nodes/{node}/qemu").unwrap(); // Path with elements: ["nodes", "{node}", "qemu"] let err = Path::try_from("invalid"); // Err(()) ``` -------------------------------- ### QEMU Virtual Machine Management Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Provides access to manage QEMU virtual machines on a specific node, including listing, creating, starting, stopping, and configuring VMs. ```APIDOC ## QEMU VM Operations on Node ### Description Manage QEMU virtual machines on a specific node. ### Method GET, POST, DELETE ### Endpoint /nodes/{node}/qemu /nodes/{node}/qemu/{vmid} /nodes/{node}/qemu/{vmid}/status/start /nodes/{node}/qemu/{vmid}/status/stop /nodes/{node}/qemu/{vmid}/status/reset ### Parameters #### Path Parameters - **node** (string) - Required - The name of the node. - **vmid** (integer) - Required - The ID of the virtual machine. ### Request Example #### List VMs ```bash curl -X GET "https:///api2/json/nodes/{node}/qemu" ``` #### Start VM ```bash curl -X POST "https:///api2/json/nodes/{node}/qemu/{vmid}/status/start" ``` ### Response #### Success Response (200) - **vmid** (integer) - The ID of the VM. - **name** (string) - The name of the VM. - **status** (string) - The current status of the VM (e.g., "running", "stopped"). - **maxcpu** (integer) - Maximum CPU cores allocated. - **maxmem** (integer) - Maximum memory allocated in bytes. #### Response Example (List VMs) ```json { "data": [ { "vmid": 100, "name": "ubuntu-vm", "status": "running", "maxcpu": 2, "maxmem": 2147483648 } ] } ``` #### Response Example (VM Status) ```json { "data": { "status": "running" } } ``` ``` -------------------------------- ### Get API Module Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/README.md Shows how to obtain a client for a specific API module, such as nodes or storage, after the main client has been initialized. ```rust // 2. Get client for API module (nodes, storage, access, etc.) // NodesClient::new(client) // AccessClient::new(client) ``` -------------------------------- ### Create VM Parameters Structure Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/types.md Defines the parameters for creating a virtual machine, including memory, name, and optional start flag. Uses custom serialization/deserialization for specific types. ```rust #[derive(Serialize, Deserialize)] pub struct CreateVmParams { pub vmid: VmId, #[serde( serialize_with = "crate::types::serialize_int", deserialize_with = "crate::types::deserialize_int" )] pub memory: i128, pub name: VmNameStr, #[serde( serialize_with = "crate::types::serialize_bool_optional", deserialize_with = "crate::types::deserialize_bool_optional" )] pub start: Option, } ``` -------------------------------- ### Display Formatting Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/path.md Formats the Path struct back into a string representation, ensuring it starts with a leading slash. ```APIDOC ## Display Formatting ```rust impl core::fmt::Display for Path ``` Formats path back to string with leading slash. **Examples:** ```rust use proxmox_api::Path; use std::convert::TryFrom; let path = Path::try_from("/nodes/{node}/qemu").unwrap(); println!("{}", path); // "/nodes/{node}/qemu" ``` ``` -------------------------------- ### AuthState::new Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Creates a new AuthState instance with no authentication initially set. This is the starting point for managing authentication credentials. ```APIDOC ## AuthState::new ### Description Creates a new `AuthState` with no authentication set. ### Signature ```rust pub fn new() -> Self ``` ### Example ```rust let auth = AuthState::new(); ``` ``` -------------------------------- ### Mixed Authentication Example Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Demonstrates setting both an API token and a ticket/CSRF token simultaneously, although this is an unusual configuration. The generated headers will include all three authentication methods. ```rust // Can set both API token and ticket (though unusual) auth.set_api_token("root", "pam", "token-id", "secret"); auth.set_csrf("ticket-value".to_string(), "csrf-value".to_string()); // Headers will include all three auth methods for (name, value) in auth.headers() { println!("{}: {}", name, value); } // Output: // Cookie: PVEAuthCookie=ticket-value // CSRFPreventionToken: csrf-value // Authorization: PVEAPIToken=root@pam!token-id=secret ``` -------------------------------- ### Create New AuthState Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Initializes a new AuthState instance with no authentication credentials set. This is the starting point for managing authentication. ```rust let auth = AuthState::new(); ``` -------------------------------- ### QEMU Virtual Machine Management Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Provides access to QEMU virtual machine management features for a specific node. This includes listing, creating, starting, stopping, and managing VM configurations and snapshots. ```rust pub fn qemu(&self) -> qemu::QemuClient ``` ```rust let qemu = node_client.qemu(); // List VMs let vms = qemu.get().await?; for vm in vms { println!("VM {}: {}", vm.vmid, vm.name); } // Get specific VM status let vm_status = qemu.vmid(100).status().current().get().await?; println!("VM 100 status: {:?}", vm_status.status); ``` -------------------------------- ### API Token Setup Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Demonstrates how to set an API token directly on the `AuthState` object without making an HTTP request. This is useful for pre-configured tokens. The generated headers can then be applied to HTTP requests. ```rust use proxmox_api::client::Client; // Create fresh AuthState let auth = AuthState::new(); // Set API token directly (no HTTP request needed) auth.set_api_token("root", "pam", "my-token-id", "my-token-secret"); // Generate headers for requests for (name, value) in auth.headers() { // Apply to HTTP request } ``` -------------------------------- ### Get Cluster Resources Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Use this client to list and manage all resources across the cluster. It allows filtering by resource type. ```rust pub fn resources(&self) -> resources::ResourcesClient ``` -------------------------------- ### Custom reqwest::Client Setup Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/reqwest-client.md Configures ReqwestClient with a pre-built custom `reqwest::Client` instance, allowing for advanced HTTP client configurations like custom timeouts. ```rust use reqwest::Client as ReqwestHttpClient; let http_client = ReqwestHttpClient::builder() .timeout(std::time::Duration::from_secs(30)) .build()?; let client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", Some(http_client), ).with_api_token("token-id", "secret"); ``` -------------------------------- ### Implement Version-Specific Behavior Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Use the retrieved API version to conditionally enable features. This example parses the version string and returns a list of compatible features based on the major version number. ```rust async fn get_compatible_features(client: &ReqwestClient) -> Result, Box> { let version = VersionClient::new(client.clone()); let info = version.get().await?; let (major, _minor, _patch) = parse_version(&info.version); let features = match major { 7 => vec!["lxc", "qemu", "ha"], 8 => vec!["lxc", "qemu", "ha", "ceph", "sdn"], 9 => vec!["lxc", "qemu", "ha", "ceph", "sdn", "audit-improved"], _ => vec!["lxc", "qemu"], }; Ok(features) } ``` -------------------------------- ### Get Cluster Backup Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Manage cluster-wide backup jobs. This client allows listing, creating, updating, running, and deleting backup schedules. ```rust pub fn backup(&self) -> backup::BackupClient ``` -------------------------------- ### Get Version Information Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Retrieves detailed version information about the Proxmox VE installation. This endpoint is accessible without authentication and is useful for pre-authentication checks. ```APIDOC ## GET /version ### Description Retrieves Proxmox VE version information, including version number, release, keyboard layout, repository ID, and product name. ### Method GET ### Endpoint /version ### Parameters None ### Request Example None ### Response #### Success Response (200) - **version** (String) - Version string (e.g., "8.1.3", "9.1.2") - **release** (String) - Release designation (e.g., "bookworm", "bullseye") - **keyboard** (String) - Default keyboard layout (e.g., "en-us") - **repoid** (String) - Repository identifier - **productname** (String) - Product name (e.g., "Proxmox VE") #### Response Example { "version": "8.1.3", "release": "bookworm", "keyboard": "en-us", "repoid": "pve-enterprise", "productname": "Proxmox VE" } ``` -------------------------------- ### Get Cluster Replication Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Configure and manage VM/container replication jobs across the cluster. Supports listing, creating, updating, and deleting replication schedules. ```rust pub fn replication(&self) -> replication::ReplicationClient ``` -------------------------------- ### Basic Authentication with API Token Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/README.md Demonstrates how to create a client with basic authentication using username, realm, and an API token. ```rust use proxmox_api::ReqwestClient; let client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret-token"); ``` -------------------------------- ### get Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/client.md Convenience method for making GET requests. It sends a request with query parameters and no JSON body. ```APIDOC ## GET /path ### Description Convenience method for making GET requests with query parameters. ### Method GET ### Endpoint /path ### Parameters #### Query Parameters - **query** (Serialize) - Required - The query parameters to be sent with the request. ### Request Example ```rust #[derive(Serialize)] struct ListQuery { #[serde(skip_serializing_if = "Option::is_none")] filter: Option, } let query = ListQuery { filter: None }; let vms: Vec = client.get("/nodes/pve/qemu", &query).await?; ``` ### Response #### Success Response - **R** (DeserializeOwned) - The deserialized response from the server. ``` -------------------------------- ### Build All Targets Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Builds the library with default features and generates documentation. This is the standard command for a full build. ```bash cargo build ``` -------------------------------- ### Initialize Proxmox API Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/README.md Demonstrates the first step in the typical workflow: initializing the client with credentials. This can be done using an API token, password, or ticket. ```rust // 1. Initialize client with credentials // API token, password, or ticket ``` -------------------------------- ### Get Cluster Status Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Retrieve the overall cluster status, including individual node status and statistics. Query node status and get cluster statistics. ```rust pub fn status(&self) -> status::StatusClient ``` -------------------------------- ### Create and Populate Pool Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/pools.md Demonstrates creating a new pool with an optional comment and then adding specific members (VMs) to it, updating the comment in the process. Assumes a PoolsClient instance is already available. ```rust // Create new pool let create_params = PostParams { poolid: "web-servers".to_string(), comment: Some("Web server VMs".to_string()), }; pools.post(create_params).await?; // Add VMs to pool let pool_client = pools.pool("web-servers"); let update_params = UpdateParams { members: vec![ "qemu/100".to_string(), "qemu/101".to_string(), "qemu/102".to_string(), ], comment: Some("Production web tier".to_string()), }; pool_client.put(update_params).await?; ``` -------------------------------- ### Build with All Features Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Enables all available features for the build, including CLI, HTTP client, and all API modules. Use this for comprehensive testing. ```bash cargo build --all-features ``` -------------------------------- ### Get Node Version Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Retrieves the Proxmox VE version information for a specific node. ```rust pub fn version(&self) -> version::VersionClient ``` -------------------------------- ### Initialize ReqwestClient Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/reqwest-client.md Create a new ReqwestClient instance with the base URL, username, and realm. An optional custom reqwest::Client can be provided, otherwise a default one is created. ```rust let client = ReqwestClient::new("https://pve.example.com:8006", "root", "pam", None); ``` -------------------------------- ### Initialize AccessClient with ReqwestClient Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md Demonstrates how to create an instance of AccessClient using ReqwestClient, including authentication with an API token. This client is used to interact with the Proxmox VE access API. ```rust use proxmox_api::ReqwestClient; use proxmox_api::access::AccessClient; let http_client = ReqwestClient::new("https://pve.example.com:8006", "root", "pam", None) .with_api_token("token-id", "secret"); let access = AccessClient::new(http_client); ``` -------------------------------- ### Get Storage Information Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Retrieves detailed information about a specific storage, including its available capacity. ```APIDOC ## GET /storage/{storage} ### Description Get information about a specific storage. ### Method GET ### Endpoint /storage/{storage} ### Parameters #### Path Parameters - **storage** (string) - Required - The storage ID. ### Response #### Success Response (200) - **available** (integer) - The amount of available space in bytes. ``` -------------------------------- ### Get VM Status Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Retrieves the current status of a specific virtual machine on a given node. ```APIDOC ## GET /nodes/{node}/qemu/{vmid}/status/current ### Description Retrieves the current status of a specific virtual machine. ### Method GET ### Endpoint /nodes/{node}/qemu/{vmid}/status/current ### Parameters #### Path Parameters - **node** (String) - Required - The name of the node where the VM is located. - **vmid** (Integer) - Required - The ID of the VM. ### Request Example None ### Response #### Success Response (200) - **status** (String) - The current status of the VM (e.g., 'running', 'stopped'). #### Response Example { "status": "running" } ``` -------------------------------- ### Building Dynamic API Paths Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/path.md Shows how to parse a template path and then build a concrete path by matching against it. ```rust use proxmox_api::Path; use std::convert::TryFrom; // Parse template path let template = Path::try_from("/nodes/{node}/qemu/{vmid}/status/current").unwrap(); // Iterate to build concrete path let concrete_segments = vec!["nodes", "pve", "qemu", "100", "status", "current"]; assert!(template.matches(concrete_segments.iter().map(|s| *s))); ``` -------------------------------- ### List All VMs on Nodes Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/README.md Retrieves a list of all nodes and then iterates through each node to list all associated QEMU virtual machines. ```rust use proxmox_api::nodes::NodesClient; let nodes = NodesClient::new(client); let node_list = nodes.get().await?; for node_info in node_list { let node = nodes.node(&node_info.node); let vms = node.qemu().get().await?; for vm in vms { println!("VM {}: {}", vm.vmid, vm.name); } } ``` -------------------------------- ### Generate Documentation Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Generates project documentation and automatically opens it in the default web browser. Leverages features from `[package.metadata.docs.rs]`. ```bash cargo doc --open ``` -------------------------------- ### Retrieve Authentication Ticket Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/authentication.md Gets a clone of the currently stored authentication ticket. Returns None if no ticket has been set. ```rust if let Some(ticket) = auth.auth_ticket() { println!("Ticket: {}", ticket); } ``` -------------------------------- ### Get Storage Status Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Retrieves the status of a specific storage pool. Use this to check available space and enabled status. ```rust let status = storage_client.storage("local").status().get().await?; println!("Storage enabled: {}", status.enabled); println!("Available: {} bytes", status.available); ``` -------------------------------- ### List All Storage Pools Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Retrieves a list of all available storage pools in the cluster. Use this to get an overview of all storage resources. ```rust pub async fn get(&self) -> Result, T::Error> ``` ```rust let storage_list = storage_client.get().await?; for stor in storage_list { println!("Storage: {}", stor.storage); println!(" Type: {}", stor.type_); println!(" Content: {}", stor.content); if let Some(total) = stor.total { println!(" Total: {} bytes", total); } } ``` -------------------------------- ### Get Node Status Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Retrieves detailed resource status for a specific node, including CPU, memory, and disk usage. ```APIDOC ## GET /nodes/{node}/status ### Description Retrieves the resource status for a specific node. ### Method GET ### Endpoint /nodes/{node}/status ### Parameters #### Path Parameters - **node** (String) - Required - The name of the node to get the status for. ### Request Example None ### Response #### Success Response (200) - **cpu** (f64) - CPU usage (0-1) - **mem** (u64) - Used memory in bytes - **maxmem** (u64) - Total memory in bytes - **disk** (u64) - Used disk in bytes - **maxdisk** (u64) - Total disk in bytes #### Response Example { "cpu": 0.15, "mem": 2000000000, "maxmem": 8000000000, "disk": 50000000000, "maxdisk": 100000000000 } ``` -------------------------------- ### Rust: Authenticated ProxMox API Client and VM Listing Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/00_START_HERE.md Demonstrates how to create an authenticated ReqwestClient for the ProxMox API and then access node and VM information. Ensure you have the necessary dependencies and a valid API token. ```rust use proxmox_api::ReqwestClient; use proxmox_api::nodes::NodesClient; #[tokio::main] async fn main() -> Result<(), Box> { // Create authenticated client let client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret"); // Access API endpoints let nodes = NodesClient::new(client); // List all VMs for node_info in nodes.get().await? { let node = nodes.node(&node_info.node); for vm in node.qemu().get().await? { println!("VM {}: {}", vm.vmid, vm.name); } } Ok(()) } ``` -------------------------------- ### List All Storage Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Retrieves a list of all available storage configurations. ```APIDOC ## GET /storage ### Description List all available storage configurations. ### Method GET ### Endpoint /storage ### Response #### Success Response (200) - **storage** (string) - The name of the storage. - **enabled** (integer) - Indicates if the storage is enabled (1 for enabled, 0 for disabled). - **used** (integer) - The amount of used space in bytes. - **total** (integer) - The total capacity of the storage in bytes. ``` -------------------------------- ### List All VMs Across Cluster Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Initializes the API client and iterates through all nodes to list their virtual machines. Requires API credentials and a Proxmox endpoint. ```rust use proxmox_api::ReqwestClient; use proxmox_api::nodes::NodesClient; #[tokio::main] async fn main() -> Result<(), Box> { let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret"); let nodes = NodesClient::new(http_client); // Get all nodes let node_list = nodes.get().await?; for node_info in node_list { println!("Node: {} (status: {})", node_info.node, node_info.status); // Get VMs on this node let node_client = nodes.node(&node_info.node); let vms = node_client.qemu().get().await?; for vm in vms { println!(" VM {}: {} (status: {})", vm.vmid, vm.name, vm.status); } } Ok(()) } ``` -------------------------------- ### Build CLI Binary Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Build the command-line interface binary using the 'cli' feature. This implicitly includes the 'reqwest-client' and provides an executable tool for API interactions. ```bash cargo build --features cli --release ./target/release/proxmox-api --help ``` -------------------------------- ### PathElement From &str Conversion Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/path.md Converts a string segment into a PathElement. Strings starting with '{' and ending with '}' become Placeholder, while others become Literal. ```rust use proxmox_api::PathElement; let literal = PathElement::from("nodes"); // Literal("nodes") let placeholder = PathElement::from("{node}"); // Placeholder("node") ``` -------------------------------- ### GET /access/ticket Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md Retrieves a ticket. This is a dummy endpoint primarily for formatters and login pages. It is accessible without authentication and returns empty on success. ```APIDOC ## GET /access/ticket ### Description Dummy endpoint for formatters/login pages. Accessible without authentication. ### Method GET ### Endpoint /access/ticket ### Parameters None ### Request Example ```rust access.ticket().get().await?; println!("API is reachable"); ``` ### Response #### Success Response (200) Empty on success. ``` -------------------------------- ### Bounded Integer Type Conversions Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/types.md Demonstrates construction, access, and pattern matching for bounded integer types like VmId. Shows how to create instances and handle potential errors during conversion. ```rust // Construction let vmid = VmId::new(100)?; let vmid = VmId::try_from(100)?; // Access let value: i128 = vmid.get(); let display: String = vmid.to_string(); // Pattern matching match vmid_result { Ok(id) => println!("Valid: {}", id), Err(BoundedIntegerError::ValueLower) => println!("Too low"), Err(BoundedIntegerError::ValueHigher) => println!("Too high"), } ``` -------------------------------- ### Build CLI Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Builds the command-line interface (CLI) version of the project in release mode. Produces an executable binary. ```bash cargo build --features cli --release ``` -------------------------------- ### Check API Reachability with GET /access/ticket Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/access.md Use this endpoint to verify if the API is reachable. It does not require authentication and returns an empty success response. ```rust access.ticket().get().await?; println!("API is reachable"); ``` -------------------------------- ### Get API Version Info Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Retrieve the Proxmox API version information. This can be done with an unauthenticated client or a client authenticated with an API token. ```rust let anon_client = ReqwestClient::new("https://pve.example.com:8006", "", "", None); let version = VersionClient::new(anon_client); let info = version.get().await?; // Success ``` ```rust let auth_client = ReqwestClient::new("https://pve.example.com:8006", "root", "pam", None) .with_api_token("token-id", "secret"); let version = VersionClient::new(auth_client); let info = version.get().await?; // Success ``` -------------------------------- ### Get HA Resources and Status Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Retrieve a list of High Availability resources and the status of the HA manager. Ensure the cluster client is initialized. ```rust let ha_client = cluster.ha(); // Get HA resources let ha_resources = ha_client.get().await?; // Get HA manager status let ha_status = ha_client.status().get().await?; ``` -------------------------------- ### Query Storage Availability Before VM Creation Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Checks if sufficient storage space is available before creating a new virtual machine. Compares required space with available space on a specified storage unit. ```rust let storage_info = storage.storage("local").get().await?; if let Some(available) = storage_info.available { let required_gb = 20; let required_bytes = required_gb * 1_000_000_000; if available > required_bytes { println!("Sufficient storage available"); // Create VM... } else { println!("Insufficient storage"); } } ``` -------------------------------- ### Cluster Resources Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Provides access to cluster-wide resource management, including listing all resources, getting resource status, and filtering by type. ```APIDOC ## Cluster Resources ### Description Provides access to cluster-wide resource management. ### Method GET ### Endpoint /cluster/resources ### Parameters #### Query Parameters - **type** (string) - Optional - Filter by type (nodes, VMs, containers, storage) ### Response #### Success Response (200) - **resources** (array) - List of cluster resources - **status** (string) - Status of the resource ### Response Example { "example": "{\"resources\": [{\"id\": \"vm/100\", \"type\": \"vm\", \"status\": \"running\"}], \"status\": \"ok\"}" } ``` -------------------------------- ### Documentation Build Configuration Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Specify features to be enabled when building documentation for the proxmox-api crate on docs.rs. ```toml [package.metadata.docs.rs] features = ["default", "reqwest-client"] ``` -------------------------------- ### Get Cluster Log Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Access and filter the cluster-wide audit log. This client enables reading log entries and applying filters. ```rust pub fn log(&self) -> log::LogClient ``` -------------------------------- ### Check Cluster Status and Resources Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Initializes the HTTP client and cluster client, then fetches available endpoints, cluster status, and lists all resources. Requires `proxmox_api` and `tokio` crates. ```rust use proxmox_api::ReqwestClient; use proxmox_api::cluster::ClusterClient; #[tokio::main] async fn main() -> Result<(), Box> { let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret"); let cluster = ClusterClient::new(http_client); // Check available endpoints let endpoints = cluster.get().await?; println!("Cluster endpoints: {:?}", endpoints); // Get cluster status let status = cluster.status().get().await?; println!("Cluster status: {:?}", status); // List all resources let resources = cluster.resources().get().await?; println!("Total resources: {}", resources.len()); Ok(()) } ``` -------------------------------- ### Get Proxmox VE Version Information Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Retrieves Proxmox VE version information. This method is accessible without authentication, making it useful for pre-authentication checks. ```rust let version_info = version_client.get().await?; println!("Proxmox VE version: {}", version_info.version); println!("Release: {}", version_info.release); println!("Keyboard: {}", version_info.keyboard); ``` -------------------------------- ### Check Available Storage Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/storage.md Lists all available storage units, filtering for enabled ones and displaying their usage percentage. Requires setting up an HTTP client with authentication. ```rust use proxmox_api::ReqwestClient; use proxmox_api::storage::StorageClient; #[tokio::main] async fn main() -> Result<(), Box> { let http_client = ReqwestClient::new( "https://pve.example.com:8006", "root", "pam", None, ).with_api_token("token-id", "secret"); let storage = StorageClient::new(http_client); // List all storage let storage_list = storage.get().await?; println!("Available storage:"); for stor in storage_list { if stor.enabled == 1 { if let (Some(used), Some(total)) = (stor.used, stor.total) { let percent = (used as f64 / total as f64) * 100.0; println!("{}: {:.2}% used ({} / {} bytes)", stor.storage, percent, used, total); } } } Ok(()) } ``` -------------------------------- ### Create API Token with Read-Only Access Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Demonstrates how to create an `ReqwestClient` configured with an API token that has read-only privileges. This is useful for auditing cluster status and resources without allowing modifications. ```rust // Token with audit-only access let client = ReqwestClient::new("...", "root", "pam", None) .with_api_token("read-only-token", "secret"); ``` -------------------------------- ### Minimal Proxmox API Configuration (Types Only) Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Include only type definitions without HTTP dependencies. Use this when you need API structures but plan to implement your own HTTP client. ```toml [dependencies] proxmox-api = { version = "0.2.0", default-features = false } ``` -------------------------------- ### Get API Version Information Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md This snippet demonstrates how to fetch the Proxmox VE version information using the `VersionClient`. It shows usage with both unauthenticated and authenticated clients. ```APIDOC ## Get API Version ### Description Retrieves the current Proxmox VE version information, including the version number, release codename, and product name. This endpoint is accessible without authentication. ### Method GET ### Endpoint /version ### Request Example ```rust // Works without API token let anon_client = ReqwestClient::new("https://pve.example.com:8006", "", "", None); let version = VersionClient::new(anon_client); let info = version.get().await?; // Success // Works with API token let auth_client = ReqwestClient::new("https://pve.example.com:8006", "root", "pam", None) .with_api_token("token-id", "secret"); let version = VersionClient::new(auth_client); let info = version.get().await?; // Success ``` ### Response #### Success Response (200) - **version** (string) - The current Proxmox VE version number. - **release** (string) - The codename of the Proxmox VE release. - **keyboard** (string) - The default keyboard layout. - **repoid** (string) - The repository ID. - **productname** (string) - The name of the product. #### Response Example ```json { "version": "9.1.2", "release": "bookworm", "keyboard": "en-us", "repoid": "pve-repo", "productname": "Proxmox VE" } ``` ``` -------------------------------- ### Proxmox API CLI Binary Configuration Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/configuration.md Include the CLI tool and all its dependencies. This configuration is for building standalone command-line applications that interact with the Proxmox API. ```toml [dependencies] proxmox-api = { version = "0.2.0", features = ["cli"] } ``` -------------------------------- ### Get Cluster HA Client Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/cluster.md Manage High Availability configurations for resources within the cluster. This includes HA resource groups and manager configuration. ```rust pub fn ha(&self) -> ha::HaClient ``` -------------------------------- ### Log Proxmox System Information Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/version.md Logs detailed system information, including product name, version, release, and keyboard layout, on startup. Useful for diagnostics. ```rust let info = version_client.get().await?; log::info!("Connected to {} version {}", info.productname, info.version); log::info!("Release: {}, Keyboard: {}", info.release, info.keyboard); ``` -------------------------------- ### LXC Container Management Source: https://github.com/datdenkikniet/proxmox-api/blob/main/_autodocs/api-reference/nodes.md Provides access to manage LXC containers on a specific node, including listing, creating, starting, stopping, and configuring containers. ```APIDOC ## LXC Container Operations on Node ### Description Manage LXC containers on a specific node. ### Method GET, POST, DELETE ### Endpoint /nodes/{node}/lxc /nodes/{node}/lxc/{vmid} ### Parameters #### Path Parameters - **node** (string) - Required - The name of the node. - **vmid** (integer) - Required - The ID of the container. ### Request Example #### List Containers ```bash curl -X GET "https:///api2/json/nodes/{node}/lxc" ``` ### Response #### Success Response (200) - **vmid** (integer) - The ID of the container. - **name** (string) - The name of the container. - **status** (string) - The current status of the container (e.g., "running", "stopped"). #### Response Example (List Containers) ```json { "data": [ { "vmid": 101, "name": "ubuntu-ct", "status": "running" } ] } ``` ```