### Install from GitHub Source: https://github.com/manageiq/manageiq-api-client-python/blob/master/README.rst Install the ManageIQ API Client directly from its GitHub repository using pip. ```bash pip install git+https://github.com/ManageIQ/manageiq-api-client-python.git ``` -------------------------------- ### Run Example Script Source: https://github.com/manageiq/manageiq-api-client-python/blob/master/README.rst Execute the example Python script after setting the necessary environment variables for authentication. ```bash python example.py ``` -------------------------------- ### Set up Python Virtual Environment Source: https://github.com/manageiq/manageiq-api-client-python/blob/master/README.rst Prepare your Python virtual environment for installation. This involves creating a virtual environment, activating it, and installing the package in editable mode. ```bash virtualenv venv source venv/bin/activate pip install -e . ``` -------------------------------- ### Configure API Credentials (Username/Password) Source: https://github.com/manageiq/manageiq-api-client-python/blob/master/README.rst Set environment variables for URL, username, and password to authenticate with the ManageIQ API. This is required before running Python API examples. ```bash export MIQURL=http://localhost:3000/api export MIQUSERNAME=admin export MIQPASSWORD=smartvm ``` -------------------------------- ### Direct HTTP Methods Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Executing raw HTTP requests (GET, POST, PUT, PATCH, DELETE, OPTIONS) directly through the client. ```APIDOC ## Direct HTTP Methods ### Description Provides direct access to HTTP methods for custom API calls when high-level abstractions are insufficient. Includes automatic retry on connection errors. ### Methods - GET - POST - PUT - PATCH - DELETE - OPTIONS ### Request Example ```python # GET request with parameters client.get('http://localhost:3000/api/vms', expand='resources', limit=10) # DELETE request client.delete('http://localhost:3000/api/services/20') ``` ``` -------------------------------- ### Find and Retrieve Entities Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Retrieve specific entities using find_by or get methods. ```python result = client.collections.vms.find_by(name='my-vm', power_state='on') ``` ```python vm = client.collections.vms.get(name='unique-vm') print(f"Found: {vm.name}") ``` -------------------------------- ### Configure API Credentials (API Token) Source: https://github.com/manageiq/manageiq-api-client-python/blob/master/README.rst Set environment variables for URL and API token for authentication. Replace `< place real token here >` with your actual token. ```bash export MIQURL=http://localhost:3000/api export MIQTOKEN=< place real token here > ``` -------------------------------- ### Initialize ManageIQClient Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Initialize the ManageIQClient with URL and authentication details. Supports username/password or token authentication. Optionally configure SSL verification and CA bundle. ```python import os from manageiq_client.api import ManageIQClient as MiqApi # Authentication with username and password url = 'http://localhost:3000/api' client = MiqApi(url, dict(user='admin', password='smartvm'), verify_ssl=True) # Authentication with API token token = os.environ.get('MIQTOKEN') client = MiqApi(url, dict(token=token), verify_ssl=True) # With custom CA bundle for SSL verification client = MiqApi( url, dict(user='admin', password='smartvm'), verify_ssl=True, ca_bundle_path='/path/to/ca-bundle.crt' ) ``` -------------------------------- ### Accessing and Using Subcollections Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Demonstrates how to access and interact with subcollections of entities, such as tags and policies, on a ManageIQ object. Requires API OPTIONS support for listing subcollections. ```python from manageiq_client.api import ManageIQClient as MiqApi client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) # Get an entity with subcollections vm = client.collections.vms(1) # List available subcollections (requires API OPTIONS support) print(f"Subcollections: {vm.subcollections}") # Output: ['tags', 'policies', 'custom_attributes', ...] # Access a subcollection directly tags = vm.tags for tag in tags: print(f"Tag: {tag.name}") # Subcollections work like regular collections tag = vm.tags.get(name='environment/production') # Collection-level subcollections info vms_collection = client.collections.vms print(f"VM collection subcollections: {vms_collection.subcollections}") # Reload entity with expanded subcollections vm.reload(expand='tags') # Access related entities through COLLECTION_MAPPING # Automatically resolves IDs to entities for fields like: # ems_id -> providers, host_id -> hosts, zone_id -> zones, etc. print(f"VM's Provider: {vm.ems.name}") # ems_id automatically resolved print(f"VM's Host: {vm.host.name}") # host_id automatically resolved ``` -------------------------------- ### Access Collections Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Access and interact with resource collections like VMs, hosts, and services. Supports listing collection names, checking existence, direct access, and retrieving all entities within a collection. ```python from manageiq_client.api import ManageIQClient as MiqApi client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) # List all available collection names print(client.collections.all_names) # Output: ['vms', 'hosts', 'providers', 'services', 'servers', ...] # Check if a collection exists if 'vms' in client.collections: print("VMs collection is available") # Access a collection directly vms_collection = client.collections.vms print(f"Collection: {vms_collection.name}") print(f"Description: {vms_collection.description}") print(f"Total count: {vms_collection.count}") # Get all entities in a collection (with full data) all_vms = client.collections.vms.all for vm in all_vms: print(f"VM: {vm.name} (ID: {vm.id})") # Iterate over a collection for vm in client.collections.vms: print(f"Processing VM: {vm.name}") ``` -------------------------------- ### Handling API Exceptions Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Illustrates how to catch and handle various exceptions raised by the ManageIQ API client, including API errors, connection failures, invalid responses, and resource not found errors. ```python from manageiq_client.api import ManageIQClient as MiqApi, APIException client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) # Handle API exceptions try: # Attempt to get non-existent resource vm = client.get('http://localhost:3000/api/vms/99999') except APIException as e: print(f"API Error: {e}") # Output: ActiveRecord::RecordNotFound: Couldn't find Vm with 'id'=99999 # Access response details print(f"HTTP Status: {client.response.status_code}") # Handle entity not found via collection.get() try: vm = client.collections.vms.get(name='non-existent-vm') except ValueError as e: print(f"Not found: {e}") # Output: No such 'vms' matching query {'name': 'non-existent-vm'}! # Handle invalid authentication try: bad_client = MiqApi('http://localhost:3000/api', {'invalid': 'auth'}) except ValueError as e: print(f"Auth error: {e}") # Output: Unknown values provided for auth # Handle invalid filter operators from manageiq_client.filters import Q try: q = Q('name', 'invalid_op', 'value') except ValueError as e: print(f"Filter error: {e}") # Output: Invalid operator invalid_op # Safe existence check vm = client.collections.vms(1) if vm.exists: print(f"VM {vm.name} found") else: print("VM not found") ``` -------------------------------- ### Access API Version Information Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Retrieve and interact with ManageIQ API version details after client initialization. Allows checking current, available, and latest versions, and switching to a specific version. ```python # Access API version information print(f"ManageIQ API Version: {client.version}") print(f"Available versions: {client.versions}") print(f"Latest version: {client.latest_version}") print(f"On latest version: {client.on_latest_version}") # Switch to a specific API version client_v2 = client.api_version('2.4.0') ``` -------------------------------- ### Manage Collection and Entity Actions Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Dynamically discover and execute actions on collections or entities using various HTTP methods. ```python from manageiq_client.api import ManageIQClient as MiqApi client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) services = client.collections.services services.reload() print(f"Available actions: {services.action.all}") new_service = services.action.create( name='My Service', description='A test service' ) print(f"Created service ID: {new_service.id}") service = client.collections.services(20) print(f"Entity actions: {service.action.all}") service.action.edit(name='Updated Name') service.action.edit.POST(name='Updated via POST') service.action.edit.PATCH({ "action": "edit", "path": "name", "value": "Updated via PATCH" }) service.action.edit.PUT(name='Updated via PUT', description='New description') service.action.delete.POST() service.action.delete.DELETE() vms = client.collections.vms.all[:5] client.collections.vms.action.stop(*vms) result = services.action.execute_action('create', name='New Service') result = service.action.execute_action('edit', action_method='PUT', name='New Name') ``` -------------------------------- ### Filter Collections with Q Objects Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Use Q objects to construct complex queries for filtering collections. Supports logical operators and dictionary-based criteria. ```python result = client.collections.vms.filter(Q('name', '=', 'my-vm')) print(f"Found {len(result)} VMs") for vm in result: print(f" - {vm.name}") ``` ```python result = client.collections.vms.filter(Q('memory', '>', 4096)) ``` ```python result = client.collections.vms.filter( Q('name', '=', 'prod-vm') & Q('power_state', '=', 'on') ) ``` ```python result = client.collections.vms.filter( Q('name', '=', 'web-server') | Q('name', '=', 'app-server') ) ``` ```python result = client.collections.vms.filter( Q('vendor', '=', 'vmware') & Q('power_state', '=', 'on') | Q('name', '=', 'critical-vm') ) ``` ```python result = client.collections.vms.filter(Q.from_dict({ 'vendor': 'vmware', 'power_state': 'on' })) ``` -------------------------------- ### Collection and Entity Actions Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Performing dynamic actions on collections and entities using various HTTP methods. ```APIDOC ## Collection and Entity Actions ### Description Actions allow performing operations like create, edit, or delete on collections and entities. The API dynamically discovers available actions. ### Method Supports POST, PUT, PATCH, and DELETE via the `action` attribute. ### Request Example ```python # Create a new service services.action.create(name='My Service', description='A test service') # Edit entity using PATCH service.action.edit.PATCH({"action": "edit", "path": "name", "value": "Updated"}) ``` ``` -------------------------------- ### Query Filtering with Q Class Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Utilize the Q class for Django-style query filtering on collections. Supports comparison operators and logical chaining for complex filter construction. ```python from manageiq_client.api import ManageIQClient as MiqApi from manageiq_client.filters import Q client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) ``` -------------------------------- ### Filtering Collections Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Methods for querying and filtering collections like VMs using logical operators and dictionary-based criteria. ```APIDOC ## Filtering Collections ### Description Use the `filter` method on collections to retrieve specific resources based on criteria. Supports logical operators (=, !=, <, <=, >=, >) and combinations using AND (&) or OR (|). ### Parameters #### Request Body - **Q** (object) - Required - Query object constructed with field, operator, and value. ### Request Example ```python client.collections.vms.filter(Q('name', '=', 'my-vm')) ``` ``` -------------------------------- ### Raw Filtering and Result Metadata Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Perform custom filter string queries and access search result properties. ```python result = client.collections.vms.raw_filter(['name=test*', 'power_state=on']) print(f"Total count: {result.count}") print(f"Returned count: {result.subcount}") ``` -------------------------------- ### Execute Direct HTTP Requests Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Perform low-level HTTP operations with automatic retry logic. ```python from manageiq_client.api import ManageIQClient as MiqApi client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) result = client.get('http://localhost:3000/api/vms', expand='resources', limit=10) print(f"Retrieved {len(result.get('resources', []))} VMs") result = client.post( 'http://localhost:3000/api/services', action='create', resource={'name': 'New Service', 'description': 'Created via POST'} ) result = client.put( 'http://localhost:3000/api/services/20', name='Replaced Service', description='Fully replaced' ) result = client.patch( 'http://localhost:3000/api/services/20', {"action": "edit", "path": "name", "value": "Patched Name"} ) result = client.delete('http://localhost:3000/api/services/20') options = client.options('http://localhost:3000/api/vms') print(f"Subcollections: {options.get('subcollections', [])}") response = client.response print(f"Status code: {response.status_code}") print(f"Request method: {response.request.method}") ``` -------------------------------- ### Retrieve Entities by ID Source: https://context7.com/manageiq/manageiq-api-client-python/llms.txt Retrieve individual resources (entities) by their ID from a collection or directly from the client. Supports specifying attributes to include and reloading entity data. ```python from manageiq_client.api import ManageIQClient as MiqApi client = MiqApi('http://localhost:3000/api', dict(user='admin', password='smartvm')) # Get entity by ID from collection vm = client.collections.vms(1) print(f"VM Name: {vm.name}") print(f"VM Href: {vm._href}") # Get entity directly from API client vm = client.get_entity('vms', 1) print(f"VM: {vm.name}") # Get entity with specific attributes included vm = client.get_entity('vms', 1, attributes='region_number') print(f"VM Region: {vm.region_number}") # Get entity from collection with attributes server = client.collections.servers(1, 'region_number') print(f"Server: {server.name}, Region: {server.region_number}") # Get all entities with specific attributes servers = client.collections.servers.all_include_attributes(['region_number', 'zone_id']) for server in servers: print(f"Server: {server.name}, Region: {server.region_number}") # Reload entity to refresh data vm.reload() # Reload with expanded subcollections vm.reload(expand='resources') vm.reload(expand=['tags', 'custom_attributes']) # Check if entity exists if vm.exists: print(f"VM {vm.name} exists") # Wait for entity to exist or not exist vm.wait_exists(timeout=60) vm.wait_not_exists(timeout=120) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.