### Install Dependencies and Start Dev Server
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/AGENTS.md
Install npm dependencies and start the Docusaurus development server.
```bash
cd docs && npm install # Install deps
cd docs && npm start # Dev server at localhost:3000
```
--------------------------------
### Development setup with UV - Install all groups and extras
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs all development dependencies and optional extras using UV, a fast Python dependency manager.
```bash
uv sync --all-groups --all-extras
```
--------------------------------
### Manual Async Tracking Setup
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
Manually start an async tracking session using `start_tracking`. Only objects being saved (created or updated) are tracked. Ensure the client is configured.
```python
from infrahub_sdk.client import InfrahubClient
client = InfrahubClient(address="http://localhost:8000")
await client.start_tracking(identifier="my_tracking_session")
node = await client.create(kind="MyNodeKind", data={"name": "Example"})
await node.save()
```
--------------------------------
### Development setup with UV - Install linting dependencies
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs only the linting-related dependencies using UV.
```bash
uv sync --group lint
```
--------------------------------
### Development setup with UV - Install testing dependencies
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs only the testing-related dependencies using UV.
```bash
uv sync --group tests
```
--------------------------------
### Manual Sync Tracking Setup
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
Manually start a sync tracking session using `start_tracking`. Only objects being saved (created or updated) are tracked. Ensure the client is configured.
```python
from infrahub_sdk.client_sync import InfrahubClientSync
client = InfrahubClientSync(address="http://localhost:8000")
client.start_tracking(identifier="my_tracking_session")
node = client.create(kind="MyNodeKind", data={"name": "Example"})
node.save()
```
--------------------------------
### Install Dependencies
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/README.md
Navigate to the docs directory and install project dependencies using npm.
```console
cd docs
npm install
```
--------------------------------
### Install Infrahub SDK with all extras
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs the Infrahub SDK along with all available optional extras.
```bash
pip install 'infrahub-sdk[all]'
```
--------------------------------
### Async Hello World Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
A basic asynchronous example to verify Infrahub client connection by querying accounts. Ensure the client is configured correctly before running.
```python
import asyncio
from infrahub_sdk import Config, InfrahubClient
async def hello_world():
client = InfrahubClient(config=Config(address="http://localhost:8000"))
# Try to query accounts to validate connection
try:
accounts = await client.all(kind="CoreAccount")
print(f"Successfully connected to Infrahub! Found {len(accounts)} account(s)")
except Exception as e:
print(f"Something went wrong: {e}")
asyncio.run(hello_world())
```
--------------------------------
### Development setup with UV - Install CLI dependencies
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs only the command-line interface (CLI) related dependencies using UV.
```bash
uv sync --group ctl
```
--------------------------------
### Install and Run Commands
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/AGENTS.md
Commands for installing dependencies, formatting code, linting, generating and validating documentation, and running tests.
```bash
uv sync --all-groups --all-extras # Install all deps
```
```bash
uv run invoke format # Format code
```
```bash
uv run invoke lint # Full pipeline: ruff, yamllint, ty, mypy, markdownlint, vale
```
```bash
uv run invoke lint-code # All linters for Python code
```
```bash
uv run invoke docs-generate # Generate all docs (CLI + SDK)
```
```bash
uv run invoke docs-validate # Check generated docs match committed version
```
```bash
uv run pytest tests/unit/ # Unit tests
```
```bash
uv run pytest tests/integration/ # Integration tests
```
--------------------------------
### Install Infrahub SDK
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs the base Infrahub SDK using pip. It's recommended to do this within a virtual environment.
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install infrahub-sdk
```
--------------------------------
### Start Local Development Server
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/README.md
Start a local development server to view and test changes live. Changes are reflected without restarting.
```console
npm start
```
--------------------------------
### Install Infrahub SDK with pip
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/introduction.mdx
Installs the Infrahub SDK using 'pip'. Optional extras are available for additional functionality.
```bash
pip install infrahub-sdk
```
```bash
pip install 'infrahub-sdk[ctl]'
```
```bash
pip install 'infrahub-sdk[tests]'
```
```bash
pip install 'infrahub-sdk[all]'
```
--------------------------------
### Install Infrahub SDK with tests extra
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs the Infrahub SDK with the 'tests' extra, which includes components for the testing framework of Transforms, Queries, and Checks.
```bash
pip install 'infrahub-sdk[tests]'
```
--------------------------------
### Install Infrahub SDK with uv
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/introduction.mdx
Installs the Infrahub SDK using the 'uv' package manager. Optional extras are available for additional functionality.
```bash
uv add infrahub-sdk
```
```bash
uv add 'infrahub-sdk[ctl]'
```
```bash
uv add 'infrahub-sdk[tests]'
```
```bash
uv add 'infrahub-sdk[all]'
```
--------------------------------
### Install Infrahub SDK with ctl extra
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/README.md
Installs the Infrahub SDK with the 'ctl' extra, which provides the 'infrahubctl' command for interacting with an Infrahub instance.
```bash
pip install 'infrahub-sdk[ctl]'
```
--------------------------------
### Setup Script Execution
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/skills/speckit-plan/SKILL.md
This command executes the setup script for the planning phase, outputting results in JSON format. It highlights the need for proper escaping of single quotes within arguments.
```bash
.specify/scripts/bash/setup-plan.sh --json
```
--------------------------------
### Start and End Tracking Session (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
This snippet demonstrates starting a synchronous tracking session, creating a node, saving it, and then updating the tracking information for the session.
```python
from infrahub_sdk.client_sync import InfrahubClientSync
client = InfrahubClientSync(address="http://localhost:8000")
client.start_tracking(identifier="my_tracking_session")
node = client.create(kind="MyNodeKind", data={"name": "Example"})
node.save()
# Update tracking information for sync client
client.group_context.update_group()
```
--------------------------------
### Start and End Tracking Session (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
This snippet demonstrates starting an asynchronous tracking session, creating a node, saving it, and then updating the tracking information for the session.
```python
from infrahub_sdk.client import InfrahubClient
client = InfrahubClient(address="http://localhost:8000")
await client.start_tracking(identifier="my_tracking_session")
node = await client.create(kind="MyNodeKind", data={"name": "Example"})
await node.save()
# Update tracking information for async client
await client.group_context.update_group()
```
--------------------------------
### MDX Structure with Tabs and Callouts
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/AGENTS.md
Example of an MDX file structure using Tabs for async/sync examples and callouts for important notes.
```mdx
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
...
...
:::warning
Use callouts for important notes.
:::
```
--------------------------------
### Run Quickstart Validation
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-end-user-cli/tasks.md
Manually executes the steps outlined in the quickstart.md file against a test instance to ensure they function correctly.
```shell
quickstart.md validation
```
--------------------------------
### Sync Client Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/introduction.mdx
Demonstrates creating and querying tags using the synchronous Infrahub client. Suitable for straightforward scripting.
```python
from infrahub_sdk import InfrahubClientSync
client = InfrahubClientSync()
# Create a new tag and save it
tag = client.create(
kind="BuiltinTag",
name="staging",
description="Resources in the staging environment",
)
tag.save()
# Query all tags
tags = client.all(kind="BuiltinTag")
for tag in tags:
print(f"{tag.name.value} — {tag.description.value}")
```
--------------------------------
### CLI Test Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/tests/AGENTS.md
An example of testing a command-line interface command using CliRunner.
```python
def test_cli_command():
runner = CliRunner()
result = runner.invoke(app, ["command", "--flag"])
assert result.exit_code == 0
```
--------------------------------
### Start Tracking with Custom Parameters (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
Use this snippet to start a synchronous tracking session with custom parameters like data source and analysis type, and to enable automatic deletion of unused nodes.
```python
params = {
"data_source": "external",
"analysis_type": "ipam_data"
}
client.start_tracking(
identifier="weekly_analysis",
params=params,
delete_unused_nodes=True
)
```
--------------------------------
### Async Client Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/introduction.mdx
Demonstrates creating and querying tags using the asynchronous Infrahub client. Use this for applications benefiting from concurrent I/O.
```python
import asyncio
from infrahub_sdk import InfrahubClient
async def main():
client = InfrahubClient()
# Create a new tag and save it
tag = await client.create(
kind="BuiltinTag",
name="staging",
description="Resources in the staging environment",
)
await tag.save()
# Query all tags
tags = await client.all(kind="BuiltinTag")
for tag in tags:
print(f"{tag.name.value} — {tag.description.value}")
asyncio.run(main())
```
--------------------------------
### Create Node (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Use the sync `create` method to instantiate a node in memory and `save` it to Infrahub. This example creates a 'TestDevice' with a specified name.
```python
device = client.create(kind="TestDevice", name="atl1-edge1")
device.save()
```
--------------------------------
### Start Tracking with Custom Parameters (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/tracking.mdx
Use this snippet to start an asynchronous tracking session with custom parameters like data source and analysis type, and to enable automatic deletion of unused nodes.
```python
params = {
"data_source": "external",
"analysis_type": "ipam_data"
}
await client.start_tracking(
identifier="weekly_analysis",
params=params,
delete_unused_nodes=True
)
```
--------------------------------
### Get Method Overloads for InfraHub SDK
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Demonstrates various overloads for the `get` method in the InfraHub SDK, allowing retrieval of data with different parameters and return types. Use these when fetching specific resources or collections.
```python
get(self, kind: type[SchemaTypeSync], raise_when_missing: Literal[False], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaTypeSync | None
```
```python
get(self, kind: type[SchemaTypeSync], raise_when_missing: Literal[True], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaTypeSync
```
```python
get(self, kind: type[SchemaTypeSync], raise_when_missing: bool = ..., at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaTypeSync
```
```python
get(self, kind: str, raise_when_missing: Literal[False], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNodeSync | None
```
```python
get(self, kind: str, raise_when_missing: Literal[True], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNodeSync
```
```python
get(self, kind: str, raise_when_missing: bool = ..., at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNodeSync
```
```python
get(self, kind: str | type[SchemaTypeSync], raise_when_missing: bool = True, at: Timestamp | None = None, branch: str | None = None, timeout: int | None = None, id: str | None = None, hfid: list[str] | None = None, include: list[str] | None = None, exclude: list[str] | None = None, populate_store: bool = True, fragment: bool = False, prefetch_relationships: bool = False, property: bool = False, include_metadata: bool = False, query_name: str | None = None, **kwargs: Any) -> InfrahubNodeSync | SchemaTypeSync | None
```
--------------------------------
### start_tracking
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Starts tracking resources with optional parameters for identification, deletion of unused nodes, and grouping.
```APIDOC
## start_tracking
### Description
Starts tracking resources with optional parameters for identification, deletion of unused nodes, and grouping.
### Method Signature
`start_tracking(self, identifier: str | None = None, params: dict[str, Any] | None = None, delete_unused_nodes: bool = False, group_type: str | None = None, group_params: dict[str, Any] | None = None, branch: str | None = None) -> Self`
### Parameters
- `identifier` (str | None): An identifier for the tracking session.
- `params` (dict[str, Any] | None): Additional parameters for tracking.
- `delete_unused_nodes` (bool): Whether to delete unused nodes. Defaults to False.
- `group_type` (str | None): The type of group for tracking.
- `group_params` (dict[str, Any] | None): Parameters for the group.
- `branch` (str | None): The name of the branch to track from.
```
--------------------------------
### Create Node (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Use the async `create` method to instantiate a node in memory and `save` it to Infrahub. This example creates a 'TestDevice' with a specified name.
```python
device = await client.create(kind="TestDevice", name="atl1-edge1")
await device.save()
```
--------------------------------
### Query All Nodes of a Kind (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/query_data.mdx
Use the `all` method to retrieve all nodes of a specified kind. This example retrieves all 'BuiltinTag' nodes.
```python
tags = client.all(kind="BuiltinTag")
```
--------------------------------
### infrahubctl render Usage Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/infrahubctl/infrahubctl-render.mdx
Demonstrates the basic command-line usage for rendering a local Jinja2 transform. Specify the transform name and any necessary variables.
```console
$ infrahubctl render [OPTIONS] [TRANSFORM_NAME] [VARIABLES]...
```
--------------------------------
### Start Tracking
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Initiates tracking with optional parameters for identification, grouping, and branch. Can also be configured to delete unused nodes.
```python
start_tracking(self, identifier: str | None = None, params: dict[str, Any] | None = None, delete_unused_nodes: bool = False, group_type: str | None = None, group_params: dict[str, Any] | None = None, branch: str | None = None) -> Self
```
--------------------------------
### Query All Nodes of a Kind (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/query_data.mdx
Use the `all` method to retrieve all nodes of a specified kind. This example retrieves all 'BuiltinTag' nodes.
```python
tags = await client.all(kind="BuiltinTag")
```
--------------------------------
### GraphQL Query Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/python-typing.mdx
Define your GraphQL queries in .gql files. Ensure each query has a unique name for generated Python files.
```graphql
# queries/get_tags.gql
query GetAllTags {
BuiltinTag {
edges {
node {
__typename
name {
value
}
}
}
}
}
```
--------------------------------
### Build and Test Documentation
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/AGENTS.md
Build the static documentation site and run utility tests.
```bash
cd docs && npm run build # Build static site
cd docs && npm test # Run sidebar utility tests
```
--------------------------------
### Update Node Attribute (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Retrieve a node using `get`, modify its attributes directly, and then call `save` to persist the changes synchronously. This example renames an interface.
```python
interface = client.get(kind="TestInterface", name__value="Ethernet1")
interface.name.value = "Ethernet3"
interface.save()
```
--------------------------------
### Update Node Attribute (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Retrieve a node using `get`, modify its attributes directly, and then call `save` to persist the changes asynchronously. This example renames an interface.
```python
interface = await client.get(kind="TestInterface", name__value="Ethernet1")
interface.name.value = "Ethernet3"
await interface.save()
```
--------------------------------
### Query Single Node with Filter (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/query_data.mdx
Use the `get` method to retrieve a single node of a specific kind that matches the provided filter. This example filters for a 'BuiltinTag' with the name 'RED'.
```python
tag = client.get(kind="BuiltinTag", name__value="RED")
```
--------------------------------
### Create Node with One-to-One Relation (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Create a node and establish a one-to-one relationship by passing a related node object. This example links a 'TestDevice' to a 'TestSite'.
```python
site = client.get(kind="TestSite", name__value="atl1")
device = client.create(kind="TestDevice", name="atl1-edge1", site=site)
device.save()
```
--------------------------------
### Query Single Node with Filter (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/query_data.mdx
Use the `get` method to retrieve a single node of a specific kind that matches the provided filter. This example filters for a 'BuiltinTag' with the name 'RED'.
```python
tag = await client.get(kind="BuiltinTag", name__value="RED")
```
--------------------------------
### Download File Examples
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/node/node.mdx
Demonstrates downloading file content to memory, streaming to a file path, and skipping download if the local file checksum matches the server's.
```python
>>> # Download to memory
>>> content = contract.download_file()
>>> # Stream to file (memory-efficient for large files)
>>> bytes_written = contract.download_file(dest=Path("/tmp/contract.pdf"))
>>> # Skip download if local file already matches server checksum
>>> bytes_written = contract.download_file(
... dest=Path("/tmp/contract.pdf"), skip_if_unchanged=True
... )
```
--------------------------------
### Generate All Docs
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/knowledge/doc-generation.md
Use this command to generate all CLI and SDK documentation.
```bash
uv run invoke docs-generate
```
--------------------------------
### Async Test Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/tests/AGENTS.md
An example of an asynchronous test function. No decorator is needed as async mode is enabled globally. Uses httpx_mock for HTTP mocking.
```python
async def test_async_operation(httpx_mock: HTTPXMock):
httpx_mock.add_response(
url="http://localhost:8000/api/graphql",
json={"data": {"result": "success"}},
)
client = InfrahubClient()
result = await client.execute(query="...")
assert result is not None
```
--------------------------------
### InfrahubClient get method signature
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Signature for the get method of InfrahubClient, used to retrieve schema types. Supports various parameters for filtering and fetching.
```python
get(self, kind: type[SchemaType], raise_when_missing: Literal[False], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaType | None
```
```python
get(self, kind: type[SchemaType], raise_when_missing: Literal[True], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaType
```
```python
get(self, kind: type[SchemaType], raise_when_missing: bool = ..., at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> SchemaType
```
```python
get(self, kind: str, raise_when_missing: Literal[False], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNode | None
```
```python
get(self, kind: str, raise_when_missing: Literal[True], at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNode
```
```python
get(self, kind: str, raise_when_missing: bool = ..., at: Timestamp | None = ..., branch: str | None = ..., timeout: int | None = ..., id: str | None = ..., hfid: list[str] | None = ..., include: list[str] | None = ..., exclude: list[str] | None = ..., populate_store: bool = ..., fragment: bool = ..., prefetch_relationships: bool = ..., property: bool = ..., include_metadata: bool = ..., query_name: str | None = ..., **kwargs: Any) -> InfrahubNode
```
```python
get(self, kind: str | type[SchemaType], raise_when_missing: bool = True, at: Timestamp | None = None, branch: str | None = None, timeout: int | None = None, id: str | None = None, hfid: list[str] | None = None, include: list[str] | None = None, exclude: list[str] | None = None, populate_store: bool = True, fragment: bool = False, prefetch_relationships: bool = False, property: bool = False, include_metadata: bool = False, query_name: str | None = None, **kwargs: Any) -> InfrahubNode | SchemaType | None
```
--------------------------------
### Get object and retrieve from store (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/store.mdx
Retrieves a 'BuiltinTag' object and then gets it from the local store using its ID. This demonstrates how objects fetched via `client.get` are automatically cached.
```python
tag = await client.get(kind="BuiltinTag", name__value="RED")
tag_in_store = client.store.get(key=tag.id)
```
--------------------------------
### Validate `infrahubctl get ` MVP
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-end-user-cli/tasks.md
Stops development after User Story 1 (Query) to validate that the `infrahubctl get ` command functions correctly with all specified output formats.
```shell
infrahubctl get
```
--------------------------------
### Serve Built Website
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/README.md
Serve the generated static content from the build directory.
```console
npm run serve
```
--------------------------------
### Get object and retrieve from store (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/store.mdx
Retrieves a 'BuiltinTag' object and then gets it from the local store using its ID. This demonstrates how objects fetched via `client.get` are automatically cached in synchronous mode.
```python
tag = client.get(kind="BuiltinTag", name__value="RED")
tag_in_store = client.store.get(key=tag.id)
```
--------------------------------
### Initialize Infrahub Repository Command Usage
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/infrahubctl/infrahubctl-repository.mdx
Provides the usage for initializing a new Infrahub repository.
```console
$ infrahubctl repository init [OPTIONS]
```
--------------------------------
### Async and Sync Client Initialization
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/AGENTS.md
Instantiate both asynchronous and synchronous Infrahub clients. Always provide both versions for new features.
```python
client = InfrahubClient() # async
```
```python
client = InfrahubClientSync() # sync
```
--------------------------------
### Configure Single Proxy with Configuration Object (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
Set up a single proxy for all client requests by providing the proxy URL to the `proxy` parameter in the `Config` object for a synchronous client.
```python
from infrahub_sdk import Config, InfrahubClientSync
config = Config(proxy="http://proxy.example.com:8080")
client = InfrahubClientSync(config=config)
```
--------------------------------
### Use Separate HTTP and HTTPS Proxies (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
Initialize an asynchronous client after setting environment variables for separate HTTP and HTTPS proxies. The client will automatically use these proxy configurations.
```python
from infrahub_sdk import InfrahubClient
# Proxy configuration is read from environment variables
client = InfrahubClient()
```
--------------------------------
### Configure Single Proxy with Configuration Object (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
Set up a single proxy for all client requests by providing the proxy URL to the `proxy` parameter in the `Config` object for an asynchronous client.
```python
from infrahub_sdk import Config, InfrahubClient
config = Config(proxy="http://proxy.example.com:8080")
client = InfrahubClient(config=config)
```
--------------------------------
### Mismatched Range Lengths Error Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/topics/object_file.mdx
Shows an example that will fail validation due to mismatched range lengths in multiple fields. The ranges '[1-3]' (length 3) and '[10-15]' (length 6) cause a validation error.
```yaml
spec:
kind: BuiltinLocation
parameters:
expand_range: true
data:
- name: AMS[1-3]
description: "Datacenter [10-15]"
type: Country
```
--------------------------------
### Sync Test Example
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/tests/AGENTS.md
A standard synchronous test function.
```python
def test_sync_operation():
client = InfrahubClientSync()
# ...
```
--------------------------------
### CLI-facing Fragment Renderer Entry Point
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/infp-496-graphql-fragment-inlining/spec.md
This function loads query and fragment files from configuration and renders a self-contained GraphQL document. It raises specific errors for missing resources, duplicate fragments, or circular dependencies.
```python
def render_query(name: str, config: InfrahubRepositoryConfig, relative_path: str = ".") -> str:
"""Return a self-contained GraphQL document for the named query, with fragment definitions inlined.
Loads the query file and all declared fragment files from config, then delegates to
render_query_with_fragments.
Raises:
ResourceNotDefinedError: Query name not found in config.
FragmentFileNotFoundError: A declared fragment file path does not exist.
DuplicateFragmentError: Same fragment name declared in multiple files.
FragmentNotFoundError: Query references a fragment not found in any declared file.
CircularFragmentError: Circular dependency detected among fragments.
"""
```
--------------------------------
### Get Attribute Value
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/node/attribute.mdx
Retrieves the current value of a node attribute.
```python
value(self) -> Any
```
--------------------------------
### Use Separate HTTP and HTTPS Proxies (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
Initialize a synchronous client after setting environment variables for separate HTTP and HTTPS proxies. The client will automatically use these proxy configurations.
```python
from infrahub_sdk import InfrahubClientSync
# Proxy configuration is read from environment variables
client = InfrahubClientSync()
```
--------------------------------
### get_diff_summary
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Get a summary of the differences between two points in time on a specific branch.
```APIDOC
## get_diff_summary
### Description
Get a summary of the differences between two points in time on a specific branch.
### Method Signature
`get_diff_summary(self, branch: str, name: str | None = None, from_time: datetime | None = None, to_time: datetime | None = None, timeout: int | None = None, tracker: str | None = None) -> list[NodeDiff]`
### Parameters
#### Path Parameters
None
#### Query Parameters
- **branch** (str) - Required - The name of the branch.
- **name** (str | None) - Optional - The name of the diff. Defaults to None.
- **from_time** (datetime | None) - Optional - The starting time for the diff. Defaults to None.
- **to_time** (datetime | None) - Optional - The ending time for the diff. Defaults to None.
- **timeout** (int | None) - Optional - Timeout in seconds for the operation. Defaults to None.
- **tracker** (str | None) - Optional - Tracker for the operation.
### Returns
- list[NodeDiff] - A list of NodeDiff objects summarizing the differences.
```
--------------------------------
### Migrating from --load to Separate Download and Load Commands
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/research.md
Use this workflow to replace the functionality of the deprecated `infrahubctl marketplace download --load` command. First, download the schemas to a local directory, then load them into Infrahub.
```bash
infrahubctl marketplace download -o ./schemas
infrahubctl schema load ./schemas
```
--------------------------------
### Define BuiltinTag Objects
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/topics/object_file.mdx
Example of an Object file defining `BuiltinTag` resources with their names.
```yaml
---
apiVersion: infrahub.app/v1
kind: Object
spec:
kind: BuiltinTag
data:
- name: Blue
- name: Yellow
- name: Red
```
--------------------------------
### Schema Download Success Output
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/quickstart.md
Example of the expected success output when downloading a schema.
```text
Downloaded schema acme/network-base v1.2.0 -> schemas/network-base.yml
```
--------------------------------
### Error Output: Not Found
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/quickstart.md
Example of the expected error output when a schema or collection is not found on the marketplace.
```text
# Not found
No schema or collection named 'acme/missing' found on marketplace.infrahub.app
```
--------------------------------
### Check Prerequisites Script
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/skills/speckit-implement/SKILL.md
Execute this script from the repository root to check prerequisites and parse FEATURE_DIR and AVAILABLE_DOCS lists. Ensure all paths are absolute.
```bash
check-prerequisites.sh --json --require-tasks --include-tasks
```
--------------------------------
### Low-level Fragment Renderer Entry Point
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/infp-496-graphql-fragment-inlining/spec.md
This function takes a query string and a list of fragment file paths to render a self-contained GraphQL document. It handles syntax errors, duplicate fragments, and circular dependencies.
```python
def render_query_with_fragments(query_str: str, fragment_files: list[str]) -> str:
"""Return a self-contained GraphQL document with required fragment definitions inlined.
If the query contains no fragment spreads, query_str is returned unchanged.
Raises:
QuerySyntaxError: Query string or a fragment file contains invalid GraphQL syntax.
DuplicateFragmentError: Same fragment name declared in multiple files.
FragmentNotFoundError: Query references a fragment not found in any declared file.
CircularFragmentError: Circular dependency detected among fragments.
"""
```
--------------------------------
### Get Request Context
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Retrieves the current request context, which may be None if no context is active.
```python
request_context(self) -> RequestContext | None
```
--------------------------------
### get_diff_tree
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Get the complete diff tree with metadata and nodes. Returns None if no diff exists.
```APIDOC
## get_diff_tree
### Description
Get the complete diff tree with metadata and nodes. Returns None if no diff exists.
### Method Signature
`get_diff_tree(self, branch: str, name: str | None = None, from_time: datetime | None = None, to_time: datetime | None = None, timeout: int | None = None, tracker: str | None = None) -> DiffTreeData | None`
### Parameters
#### Path Parameters
None
#### Query Parameters
- **branch** (str) - Required - The name of the branch.
- **name** (str | None) - Optional - The name of the diff. Defaults to None.
- **from_time** (datetime | None) - Optional - The starting time for the diff. Defaults to None.
- **to_time** (datetime | None) - Optional - The ending time for the diff. Defaults to None.
- **timeout** (int | None) - Optional - Timeout in seconds for the operation. Defaults to None.
- **tracker** (str | None) - Optional - Tracker for the operation.
### Returns
- DiffTreeData | None - The complete diff tree with metadata and nodes, or None if no diff exists.
### Raises
- `ValueError`: If `from_time` is later than `to_time`.
```
--------------------------------
### Migration Example for FilterDefinition
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/infp-504-artifact-composition/data-model.md
Illustrates the migration from the old 'trusted' parameter to the new 'allowed_contexts' parameter in FilterDefinition.
```python
FilterDefinition("abs", trusted=True, source="jinja2")
FilterDefinition("safe", trusted=False, source="jinja2")
```
```python
FilterDefinition("abs", allowed_contexts=ExecutionContext.ALL, source="jinja2")
FilterDefinition("safe", allowed_contexts=ExecutionContext.LOCAL, source="jinja2")
```
--------------------------------
### Create Method Overloads for InfraHub SDK
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Illustrates the `create` method overloads for creating new resources. It accepts the resource kind, data, and an optional branch. Use these to add new entries to InfraHub.
```python
create(self, kind: str | type[SchemaTypeSync], data: dict | None = None, branch: str | None = None, timeout: int | None = None, **kwargs: Any) -> InfrahubNodeSync | SchemaTypeSync
```
```python
create(self, kind: str, data: dict | None = ..., branch: str | None = ..., **kwargs: Any) -> InfrahubNodeSync
```
```python
create(self, kind: type[SchemaTypeSync], data: dict | None = ..., branch: str | None = ..., **kwargs: Any) -> SchemaTypeSync
```
--------------------------------
### Error Output: Invalid Input
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/quickstart.md
Example of the expected error output when the provided identifier format is invalid.
```text
# Invalid input
Invalid identifier 'acme-network-base'. Expected format: namespace/name
```
--------------------------------
### Error Output: Version Not Found
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/quickstart.md
Example of the expected error output when a specified version of a schema is not published.
```text
# Version not found
Schema 'acme/network-base' has no published version '9.9.9'. Run without --version for the latest.
```
--------------------------------
### Create object and retrieve from store (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/store.mdx
Creates a new 'BuiltinTag' object, saves it, and then retrieves it from the store using its ID. This shows that newly created and saved objects are also added to the store.
```python
tag = await client.create("BuiltinTag", name="BLACK")
await tag.save()
tag_in_store = client.store.get(key=tag.id)
```
--------------------------------
### Error Output: Network Issue
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-marketplace-api-update/quickstart.md
Example of the expected error output when there is a network connectivity issue reaching the marketplace.
```text
# Network
Could not reach marketplace at https://marketplace.infrahub.app: connection timed out. Check your connection or --marketplace-url.
```
--------------------------------
### Test File Structure Convention
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/rules/python-testing-unit.md
Mirror the source structure in the tests directory. For example, `infrahub_sdk/client.py` should have its tests in `tests/unit/sdk/test_client.py`.
```text
infrahub_sdk/client.py → tests/unit/sdk/test_client.py
infrahub_sdk/ctl/commands/get.py → tests/unit/ctl/test_get.py
```
--------------------------------
### Get List of Repositories
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/sdk_ref/infrahub_sdk/client.mdx
Retrieves a list of repositories, optionally filtered by branches. Defaults to retrieving CoreGenericRepository types.
```python
get_list_repositories(self, branches: dict[str, BranchData] | None = None, kind: str = 'CoreGenericRepository') -> dict[str, RepositoryData]
```
--------------------------------
### Test Infrahub Connection and Authentication
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/client.mdx
This snippet demonstrates how to initialize the client and test the connection by querying accounts. It includes error handling for connection issues.
```python
from infrahub_sdk import Config, InfrahubClientSync
def hello_world():
client = InfrahubClientSync(config=Config(address="http://localhost:8000"))
# Try to query accounts to validate connection
try:
accounts = client.all(kind="CoreAccount")
print(f"Successfully connected to Infrahub! Found {len(accounts)} account(s)")
except Exception as e:
print(f"Something went wrong: {e}")
hello_world()
```
--------------------------------
### Project Structure: Documentation
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-end-user-cli/plan.md
Overview of the documentation directory structure for the end-user CLI feature.
```text
dev/specs/001-end-user-cli/
├── plan.md # This file
├── spec.md # Feature specification
├── research.md # Phase 0 research findings
├── data-model.md # Data model (transient structures)
├── quickstart.md # Usage quickstart guide
├── contracts/
│ └── cli-commands.md # CLI command contracts
├── checklists/
│ └── requirements.md # Spec quality checklist
└── tasks.md # Implementation tasks
```
--------------------------------
### Include Interfaces Relationship (Async)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/query_data.mdx
Retrieves a device and explicitly includes the 'interfaces' relationship. This initializes the relationship and its related nodes.
```python
device = await client.get(kind="TestDevice", name__value="atl1-edge1", include=["interfaces"])
print(device.interfaces.initialized) # True
print(device.interfaces.peers)
for interface in device.interfaces.peers:
print(interface.id, interface.display_label, interface.typename)
```
--------------------------------
### Node Operations with Infrahub Client
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/AGENTS.md
Example of fetching a node of a specific kind and saving its changes using the asynchronous client.
```python
node = await client.get(kind="NetworkDevice")
await node.save()
```
--------------------------------
### Create a Branch (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/resource-manager.mdx
Use this synchronous method to create a new branch. Ensure the client is initialized.
```python
client.branch.create("test")
```
--------------------------------
### Create Node with Data Dictionary (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/create_update_delete.mdx
Instantiate a node using a dictionary for attributes with the sync `create` method, then save it. This is useful for passing complex or dynamic data structures.
```python
data = {"name": "atl1-edge1"}
device = client.create(kind="TestDevice", data=data)
device.save()
```
--------------------------------
### Paginate Query Results
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/dev/specs/001-end-user-cli/quickstart.md
Control the number of results returned and the starting offset for pagination. This is essential for handling large datasets.
```bash
infrahubctl get InfraDevice --limit 10 --offset 20
```
--------------------------------
### Create object and retrieve from store (Sync)
Source: https://github.com/opsmill/infrahub-sdk-python/blob/stable/docs/docs/python-sdk/guides/store.mdx
Creates a new 'BuiltinTag' object, saves it, and then retrieves it from the store using its ID. This shows that newly created and saved objects are also added to the store in synchronous mode.
```python
tag = client.create("BuiltinTag", name="BLACK")
tag.save()
tag_in_store = client.store.get(key=tag.id)
```