Skip to main content
The InfrahubClient is the primary interface for interacting with Infrahub. This guide covers all configuration options and initialization patterns.

Basic Initialization

Default Configuration

The simplest way to initialize the client:
from infrahub_sdk import InfrahubClient

client = InfrahubClient()
By default, this connects to:
  • Address: http://localhost:8000
  • Timeout: 30 seconds
  • No authentication

Using Environment Variables

Configure via environment variables:
export INFRAHUB_ADDRESS="https://infrahub.example.com"
export INFRAHUB_API_TOKEN="your-api-token"
export INFRAHUB_TIMEOUT="60"
from infrahub_sdk import InfrahubClient

# Automatically reads from environment
client = InfrahubClient()

Configuration Object

Using Config Class

For explicit configuration:
from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://infrahub.example.com",
    api_token="your-api-token",
    timeout=60,
    default_branch="main"
)

client = InfrahubClient(config=config)

Configuration Parameters

address
string
default:"http://localhost:8000"
URL of your Infrahub instance
api_token
string
default:"None"
API authentication token for secure access
timeout
int
default:"30"
Request timeout in seconds
default_branch
string
default:"main"
Default branch for operations
tls_insecure
bool
default:"False"
Skip SSL certificate verification (development only)
tls_ca_file
string
default:"None"
Path to custom CA certificate file
retry
int
default:"3"
Number of retry attempts for failed requests
log_level
string
default:"INFO"
Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)

Authentication

API Token Authentication

The recommended authentication method:
from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://infrahub.example.com",
    api_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
)

client = InfrahubClient(config=config)

Generate API Token

Generate an API token through Infrahub:
  1. Log in to Infrahub web interface
  2. Navigate to Settings > API Tokens
  3. Click Generate New Token
  4. Copy the token and store it securely
Never commit API tokens to version control. Use environment variables or secure secret management.

Environment-Based Authentication

export INFRAHUB_API_TOKEN="your-token-here"
from infrahub_sdk import InfrahubClient

client = InfrahubClient()  # Automatically uses INFRAHUB_API_TOKEN

Sync vs Async Clients

Async Client (Default)

The standard async client for modern Python applications:
import asyncio
from infrahub_sdk import InfrahubClient

async def main():
    client = InfrahubClient()
    
    # All operations are async
    devices = await client.all(kind="InfraDevice")
    
    for device in devices:
        print(device.name.value)

if __name__ == "__main__":
    asyncio.run(main())

Sync Client

For synchronous contexts or legacy code:
from infrahub_sdk import InfrahubClientSync

client = InfrahubClientSync()

# Synchronous operations (no await)
devices = client.all(kind="InfraDevice")

for device in devices:
    print(device.name.value)
Use the async client (InfrahubClient) whenever possible for better performance and concurrency.

Connection Configuration

Timeout Settings

Configure timeouts for different scenarios:
from infrahub_sdk import Config, InfrahubClient

# Short timeout for health checks
quick_config = Config(
    address="https://infrahub.example.com",
    timeout=5
)
quick_client = InfrahubClient(config=quick_config)

# Long timeout for bulk operations
bulk_config = Config(
    address="https://infrahub.example.com",
    timeout=300  # 5 minutes
)
bulk_client = InfrahubClient(config=bulk_config)

Retry Configuration

Configure automatic retries:
from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://infrahub.example.com",
    retry=5,  # Retry up to 5 times
    timeout=30
)

client = InfrahubClient(config=config)

SSL/TLS Configuration

Production (Verified SSL)

from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://infrahub.example.com",
    api_token="your-token",
    # SSL verification enabled by default
)

client = InfrahubClient(config=config)

Development (Self-Signed Certificates)

Only disable SSL verification in development environments. Never in production.
from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://localhost:8000",
    tls_insecure=True  # Skip certificate verification
)

client = InfrahubClient(config=config)

Custom CA Certificate

from infrahub_sdk import Config, InfrahubClient

config = Config(
    address="https://infrahub.example.com",
    tls_ca_file="/path/to/ca-bundle.crt"
)

client = InfrahubClient(config=config)

Multiple Clients

Manage multiple Infrahub instances:
from infrahub_sdk import Config, InfrahubClient

# Production client
prod_config = Config(
    address="https://prod.infrahub.example.com",
    api_token="prod-token"
)
prod_client = InfrahubClient(config=prod_config)

# Staging client
staging_config = Config(
    address="https://staging.infrahub.example.com",
    api_token="staging-token"
)
staging_client = InfrahubClient(config=staging_config)

# Use different clients
prod_devices = await prod_client.all(kind="InfraDevice")
staging_devices = await staging_client.all(kind="InfraDevice")

Configuration Files

TOML Configuration

Create infrahub.toml:
[infrahub]
address = "https://infrahub.example.com"
api_token = "your-api-token"
timeout = 60
default_branch = "main"
log_level = "INFO"

[infrahub.tls]
insecure = false
ca_file = "/path/to/ca-bundle.crt"
Load configuration:
from infrahub_sdk import Config, InfrahubClient
import tomli

with open("infrahub.toml", "rb") as f:
    config_dict = tomli.load(f)

config = Config(**config_dict["infrahub"])
client = InfrahubClient(config=config)

Environment-Specific Configurations

import os
from infrahub_sdk import Config, InfrahubClient

env = os.getenv("ENVIRONMENT", "development")

configs = {
    "development": Config(
        address="http://localhost:8000",
        timeout=30
    ),
    "staging": Config(
        address="https://staging.infrahub.example.com",
        api_token=os.getenv("STAGING_TOKEN"),
        timeout=60
    ),
    "production": Config(
        address="https://infrahub.example.com",
        api_token=os.getenv("PROD_TOKEN"),
        timeout=120
    )
}

client = InfrahubClient(config=configs[env])

Logging Configuration

Enable Debug Logging

import logging
from infrahub_sdk import Config, InfrahubClient

# Configure SDK logging
logging.basicConfig(level=logging.DEBUG)

config = Config(
    address="https://infrahub.example.com",
    log_level="DEBUG"
)

client = InfrahubClient(config=config)

Custom Logger

import logging
from infrahub_sdk import InfrahubClient

logger = logging.getLogger("infrahub_sdk")
logger.setLevel(logging.INFO)

handler = logging.FileHandler("infrahub.log")
formatter = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
handler.setFormatter(formatter)
logger.addHandler(handler)

client = InfrahubClient()

Client Context Manager

Use the client as a context manager for proper cleanup:
import asyncio
from infrahub_sdk import InfrahubClient

async def main():
    async with InfrahubClient() as client:
        devices = await client.all(kind="InfraDevice")
        # Client automatically closes on exit

if __name__ == "__main__":
    asyncio.run(main())

Connection Validation

Validate the client connection:
import asyncio
from infrahub_sdk import InfrahubClient

async def validate_connection():
    client = InfrahubClient()
    
    try:
        # Fetch schema to test connection
        await client.schema.fetch()
        print("✓ Connected to Infrahub")
        return True
    except Exception as e:
        print(f"✗ Connection failed: {e}")
        return False

if __name__ == "__main__":
    asyncio.run(validate_connection())

Next Steps

Querying Data

Learn how to query infrastructure objects

Creating Objects

Create new infrastructure objects

Branches

Work with Git-like branches

Error Handling

Handle errors and exceptions

Build docs developers (and LLMs) love