### Get All Files Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to get all files attached to an item. ```python files = client.get_files("item_uuid", "vault_uuid") for f in files: print(f"{f.name}: {f.size} bytes") ``` -------------------------------- ### OP_CONNECT_CLIENT_ASYNC Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of setting the OP_CONNECT_CLIENT_ASYNC environment variable. ```bash export OP_CONNECT_CLIENT_ASYNC=True ``` -------------------------------- ### Get File Content Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to get the binary content of a file and write it to a local file. ```python content = client.get_file_content("file_uuid", "item_uuid", "vault_uuid") # Content is bytes, write to file with open("document.pdf", "wb") as f: f.write(content) ``` -------------------------------- ### New Client Instantiation Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to create a new client instance. ```python from onepasswordconnectsdk.client import new_client ``` -------------------------------- ### OP_CONNECT_TOKEN Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of setting the OP_CONNECT_TOKEN environment variable. ```bash export OP_CONNECT_TOKEN="my_service_account_token_here" ``` -------------------------------- ### OP_CONNECT_HOST Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of setting the OP_CONNECT_HOST environment variable. ```bash export OP_CONNECT_HOST=http://localhost:8080 # or export OP_CONNECT_HOST=https://connect.example.com ``` -------------------------------- ### Get File Metadata Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to get metadata for a specific file attached to an item. ```python file = client.get_file("file_uuid", "item_uuid", "vault_uuid") print(file.name) print(file.size) ``` -------------------------------- ### Download File Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to download a file and save it to a specified directory. ```python client.download_file("file_uuid", "item_uuid", "vault_uuid", "/tmp") # File is saved to /tmp/filename.ext ``` -------------------------------- ### Get Files Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to get all files attached to an item using the async client. ```python files = await client.get_files("item_uuid", "vault_uuid") for f in files: print(f"{f.name}: {f.size} bytes") ``` -------------------------------- ### Complete Configuration Example - Bash Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of setting up environment variables for a production-grade configuration, including host, token, timeout, default vault, and async client. ```bash #!/bin/bash # Set required credentials export OP_CONNECT_HOST="https://connect.example.com" export OP_CONNECT_TOKEN="$(cat /run/secrets/op_token)" # Set request timeout export OP_CONNECT_CLIENT_REQ_TIMEOUT=30 # Set default vault for config loaders export OP_VAULT="main_vault_uuid" # Enable async client export OP_CONNECT_CLIENT_ASYNC=True # Run application python my_app.py ``` -------------------------------- ### OP_VAULT Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of setting the OP_VAULT environment variable. ```bash export OP_VAULT=e4g7h8i9j0k1l2m3n4o5p6q7r8s9 ``` -------------------------------- ### Get File Content Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to get the binary content of a file using the async client. ```python content = await client.get_file_content("file_uuid", "item_uuid", "vault_uuid") # Content is bytes, write to file with open("document.pdf", "wb") as f: f.write(content) ``` -------------------------------- ### Get File Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to get metadata for a specific file attached to an item using the async client. ```python file = await client.get_file("file_uuid", "item_uuid", "vault_uuid") print(file.name) ``` -------------------------------- ### Install 1Password Connect SDK Source: https://github.com/1password/connect-sdk-python/blob/main/README.md Install the required package via pip. ```sh pip install onepasswordconnectsdk ``` -------------------------------- ### Run Docker Example Source: https://github.com/1password/connect-sdk-python/blob/main/example/README.md Run the Docker example, passing required environment variables for Connect token, vault ID, Connect host, and a secret string. ```bash docker run -it -e OP_CONNECT_TOKEN= -e OP_VAULT= \ -e OP_CONNECT_HOST= -e SECRET_STRING= \ python-connect-sdk-example ``` -------------------------------- ### Configuration loading example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/config.md An example demonstrating how to use the load function to populate a DatabaseConfig object from 1Password. ```python from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.config import load import os os.environ["OP_VAULT"] = "vault_uuid" class DatabaseConfig: host: 'opitem:"DB Config" opfield:server.hostname' user: 'opitem:"DB Config" opfield:credentials.username' password: 'opitem:"DB Config" opfield:credentials.password' client = new_client_from_environment() config = DatabaseConfig() load(client, config) print(config.host) # populated from 1Password print(config.user) # populated from 1Password print(config.password) # populated from 1Password ``` -------------------------------- ### File Operations Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Examples of getting summary information on all files in an item, getting a file's contents, and downloading a file's contents. ```python # Get summary information on all files stored in a given item files = connect_client.get_files(item_id, vault_id) # Get a file's contents file = connect_client.get_file_content(files[0].id, item_id, vault_id) # Download a file's contents connect_client.download_file(files[1].id, item_id, vault_id, "local/path/to/file") ``` -------------------------------- ### OP_CONNECT_CLIENT_REQ_TIMEOUT Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Examples of setting the OP_CONNECT_CLIENT_REQ_TIMEOUT environment variable for different timeout values. ```bash # 30-second timeout export OP_CONNECT_CLIENT_REQ_TIMEOUT=30 # 90-second timeout export OP_CONNECT_CLIENT_REQ_TIMEOUT=90.5 # No timeout (not recommended) export OP_CONNECT_CLIENT_REQ_TIMEOUT=None ``` -------------------------------- ### Download File Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to download a file and save it to disk using the async client. ```python await client.download_file("file_uuid", "item_uuid", "vault_uuid", "/tmp") # File is saved to /tmp/filename.ext ``` -------------------------------- ### AsyncClient Initialization Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example demonstrating how to initialize and use the AsyncClient to retrieve a vault. ```python import asyncio from onepasswordconnectsdk.client import AsyncClient async def main(): client = AsyncClient( url="http://localhost:8080", token="my_service_account_token" ) vault = await client.get_vault("vault_uuid") print(vault.name) await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### ClientConfig Initialization Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/config.md Demonstrates how to initialize ClientConfig with a custom CA certificate and with additional httpx options. ```python from onepasswordconnectsdk.client import Client from onepasswordconnectsdk.config import ClientConfig # With custom CA certificate config = ClientConfig(ca_file="/path/to/ca.crt") client = Client("https://connect.example.com", "token", config=config) # With additional httpx options config = ClientConfig( ca_file="/path/to/ca.crt", verify=False, # Disable SSL verification timeout=30.0 ) ``` -------------------------------- ### Working with Items Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Provides examples for getting a list of items in a vault, creating a new item, retrieving an item by ID or title, updating an item, and deleting an item. ```python from onepasswordconnectsdk.models import ( Item, ItemVault, Field ) vault_id = "{vault_id}" # Get a list of all items in a vault items = connect_client.get_items("{vault_id}") # Create an item new_item = Item( title="Example Login Item", category="LOGIN", tags=["1password-connect"], fields=[Field(value="new_user", purpose="USERNAME")], ) created_item = connect_client.create_item(vault_id, new_item) # Get an item item = connect_client.get_item("{item_id}", vault_id) item_by_title = connect_client.get_item_by_title("{item_title}", vault_id) # Update an item created_item.title = "New Item Title" updated_item = connect_client.update_item(created_item.id, vault_id, created_item) # Delete an item connect_client.delete_item(updated_item.id, vault_id) ``` -------------------------------- ### Entry Point Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Examples of creating client instances using `new_client_from_environment` for both synchronous and asynchronous operations. ```python # Synchronous from onepasswordconnectsdk.client import new_client_from_environment client = new_client_from_environment() # Asynchronous (if OP_CONNECT_CLIENT_ASYNC=True or is_async=True) async_client = new_client_from_environment() # Returns AsyncClient if OP_CONNECT_CLIENT_ASYNC=True ``` -------------------------------- ### Complete Configuration Example - Python Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Python code demonstrating how to create an asynchronous client from environment variables, load configuration from 1Password items, and use the loaded configuration. ```python import asyncio import os from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.config import load_dict, ClientConfig async def main(): # Verify all required environment variables are set required_vars = ["OP_CONNECT_HOST", "OP_CONNECT_TOKEN"] for var in required_vars: if not os.environ.get(var): raise RuntimeError(f"Missing required environment variable: {var}") # Optional: use custom CA certificate ca_file = os.environ.get("OP_CA_FILE") config = None if ca_file: config = ClientConfig(ca_file=ca_file) # Create client (async due to OP_CONNECT_CLIENT_ASYNC=True) client = new_client_from_environment() # Load configuration from 1Password config_spec = { "database_url": { "opitem": "Database Config", "opfield": "connection.url" }, "database_user": { "opitem": "Database Config", "opfield": "credentials.username" }, "database_password": { "opitem": "Database Config", "opfield": "credentials.password" } } config_values = load_dict(client, config_spec) # Use configuration print(f"Connecting to {config_values['database_url']}") # Cleanup await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### Get Items Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Retrieves all items in a vault, with an option to filter them. ```python # Get all items all_items = await client.get_items("vault_uuid") # Get filtered items filtered = await client.get_items("vault_uuid", 'title eq "Login"') for item in filtered: print(item.title) ``` -------------------------------- ### ClientConfig Initialization Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of initializing the ClientConfig class and using it to create a Client. ```python from onepasswordconnectsdk.config import ClientConfig from onepasswordconnectsdk.client import Client config = ClientConfig( ca_file="/path/to/ca.crt", verify=False, timeout=30.0 ) client = Client("https://connect.example.com", "token", config=config) ``` -------------------------------- ### Build Docker Image Source: https://github.com/1password/connect-sdk-python/blob/main/example/README.md Build the Docker image for the Python Connect SDK example. ```bash docker build -t python-connect-sdk-example . ``` -------------------------------- ### Get Item by Title Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Retrieves an item from a vault by its exact title. ```python item = await client.get_item_by_title("Database Password", "vault_uuid") ``` -------------------------------- ### Environment variable export example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/config.md Example of exporting environment variables to control 1Password Connect client behavior. ```bash export OP_CONNECT_HOST=http://localhost:8080 export OP_CONNECT_TOKEN=my_token_here export OP_VAULT=vault_uuid_here export OP_CONNECT_CLIENT_REQ_TIMEOUT=30 ``` -------------------------------- ### __aexit__ Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example demonstrating the proper closure of the async client session using the __aexit__ method within a try-finally block. ```python async def main(): client = AsyncClient("http://localhost:8080", "token") try: vault = await client.get_vault("vault_uuid") finally: await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### Load Configuration using Dictionary Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Example of configuring the SDK using a dictionary to specify item fields and their locations in 1Password. ```python # example dict configuration for onepasswordconnectsdk.load_dict(connect_client, CONFIG) CONFIG = { "server": { "opitem": "My database item", "opfield": "specific_section.hostname", "opvault": "some_vault_id", }, "database": { "opitem": "My database item", "opfield": ".database", "opvault": "some_vault_id", }, "username": { "opitem": "My database item", "opfield": ".username", "opvault": "some_vault_id", }, "password": { "opitem": "My database item", "opfield": ".password", "opvault": "some_vault_id", }, } values_dict = onepasswordconnectsdk.load_dict(connect_client, CONFIG) ``` -------------------------------- ### Synchronous and Asynchronous Client Initialization Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Examples of initializing both synchronous and asynchronous clients using the new_client function. ```python sync_client = new_client("http://localhost:8080", "token123") # Asynchronous client async_client = new_client("http://localhost:8080", "token123", is_async=True) ``` -------------------------------- ### Async Client Initialization and Usage Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Example demonstrating how to initialize and use an asynchronous client with the 1Password Connect SDK. ```python import asyncio # initialize async client by passing `is_async = True` async_client: Client = new_client( "{1Password_Connect_Host}", "{1Password_Connect_API_Token}", True) async def main(): vaults = await async_client.get_vaults() item = await async_client.get_item("{item_id}", "{vault_id}") # do something with vaults and item await async_client.session.aclose() # close the client gracefully when you are done asyncio.run(main()) ``` -------------------------------- ### Valid URLs Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Examples of correctly formatted URLs for the Connect server. ```text http://localhost:8080 https://connect.example.com https://connect.example.com:8443 https://10.0.0.5:8080 ``` -------------------------------- ### get_vaults Method Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to retrieve all vaults accessible to the service account. ```python vaults = await client.get_vaults() for vault in vaults: print(f"{vault.name}: {vault.items} items") ``` -------------------------------- ### Get Vault by Title Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves a vault by its name. The example shows how to access the vault's ID. ```python vault = client.get_vault_by_title("Personal") print(vault.id) ``` -------------------------------- ### Get All Vaults Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves all vaults accessible to the service account. The example iterates through the vaults and prints their names and item counts. ```python vaults = client.get_vaults() for vault in vaults: print(f"{vault.name}: {vault.items} items") ``` -------------------------------- ### Delete Item Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Example of how to delete an item from a vault using the client. ```python client.delete_item("item_uuid", "vault_uuid") ``` -------------------------------- ### Get Vault by ID Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves a vault by its ID. The example shows how to access the vault's name and items. ```python vault = client.get_vault("abc123def456") print(vault.name) print(vault.items) ``` -------------------------------- ### get_item Method Examples Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Examples demonstrating how to retrieve an item by its UUID or title within a vault, including mixed usage of UUIDs and names. ```python # By UUID item = await client.get_item("item_uuid", "vault_uuid") # By title and vault name item = await client.get_item("My Login", "Personal") # Mixed item = await client.get_item("My Login", "vault_uuid") ``` -------------------------------- ### get_vault_by_title Method Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to retrieve a vault by its name. ```python vault = await client.get_vault_by_title("Personal") print(vault.id) ``` -------------------------------- ### get_vault Method Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to retrieve a specific vault using its ID. ```python vault = await client.get_vault("abc123def456") print(vault.name) ``` -------------------------------- ### PathBuilder - build Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example demonstrating the fluent API calls to build a complete path string, including query parameters. ```python from onepasswordconnectsdk.utils import PathBuilder path = ( PathBuilder() .vaults("vault_uuid") .items("item_uuid") .query("expand", "fields") .build() ) print(path) # Output: "/v1/vaults/vault_uuid/items/item_uuid?expand=fields" ``` -------------------------------- ### PathBuilder - items Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example of building a path to a specific item. ```python path2 = PathBuilder().vaults("vault_uuid").items("item_uuid").build() ``` -------------------------------- ### Load Configuration using Class Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Example of configuring the SDK using a class with annotated attributes to specify item fields and their locations in 1Password. ```python # example class configuration for onepasswordconnectsdk.load(connect_client, CONFIG) class Config: server: 'opitem:"My database item" opvault:some_vault_id opfield:specific_section.hostname' = None database: 'opitem:"My database item" opfield:.database' = None username: 'opitem:"My database item" opfield:.username' = None password: 'opitem:"My database item" opfield:.password' = None CONFIG = Config() values_object = onepasswordconnectsdk.load(connect_client, CONFIG) ``` -------------------------------- ### Delete Item Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Example of how to delete an item from a vault using the async client. ```python await client.delete_item("item_uuid", "vault_uuid") ``` -------------------------------- ### Async Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Example demonstrating asynchronous usage of the 1Password Connect SDK with `AsyncClient`. ```python import asyncio from onepasswordconnectsdk.client import AsyncClient from onepasswordconnectsdk.models import Vault async def main(): client = AsyncClient("http://localhost:8080", "token") vault = await client.get_vault("vault_uuid") await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### Mock Client for Testing Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of using unittest.mock to create a mock client for testing the Python Connect SDK without a real 1Password Connect server. ```python import pytest from unittest.mock import Mock, patch from onepasswordconnectsdk.client import Client from onepasswordconnectsdk.models import Item, Vault def test_with_mock_client(): # Create mock client mock_client = Mock(spec=Client) # Configure mock responses mock_vault = Vault(id="vault_uuid", name="Test Vault") mock_client.get_vault.return_value = mock_vault mock_item = Item(id="item_uuid", title="Test Item") mock_client.get_item.return_value = mock_item # Use in tests vault = mock_client.get_vault("vault_uuid") assert vault.name == "Test Vault" item = mock_client.get_item("item_uuid", "vault_uuid") assert item.title == "Test Item" ``` -------------------------------- ### load_dict Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/config.md Shows how to load secrets from 1Password items into a Python dictionary using the load_dict function. ```python from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.config import load_dict client = new_client_from_environment() config = { "db_password": { "opitem": "Production Database", "opfield": "credentials.password", "opvault": "e4g7h8i9j0k1l2m3" }, "api_key": { "opitem": "API Credentials", "opfield": ".api_key", # no section "opvault": "e4g7h8i9j0k1l2m3" } } secrets = load_dict(client, config) print(secrets["db_password"]) ``` -------------------------------- ### Create Item Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Creates a new item in a specified vault. ```python from onepasswordconnectsdk.models import Item, ItemVault, Field new_item = Item( title="My Secret", category="LOGIN", vault=ItemVault(id="vault_uuid"), tags=["important"], fields=[ Field(value="secret_value", purpose="PASSWORD") ] ) created = await client.create_item("vault_uuid", new_item) print(created.id) ``` -------------------------------- ### Invalid URLs Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Examples of incorrectly formatted URLs for the Connect server, highlighting common mistakes. ```text localhost:8080 # Missing protocol connect.example.com # Missing protocol http:// # Incomplete https://connect.example.com:abc # Invalid port ``` -------------------------------- ### Custom Timeouts Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Examples of setting custom request timeouts using the OP_CONNECT_CLIENT_REQ_TIMEOUT environment variable. ```bash # 10 second timeout export OP_CONNECT_CLIENT_REQ_TIMEOUT=10 python app.py # 2 minute timeout for slow networks export OP_CONNECT_CLIENT_REQ_TIMEOUT=120 python app.py ``` -------------------------------- ### Configuration Loading Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Example of loading configuration secrets from 1Password using `load_dict`. ```python from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.config import load_dict client = new_client_from_environment() config_spec = { "db_password": { "opitem": "Database", "opfield": "credentials.password", "opvault": "vault_uuid" } } secrets = load_dict(client, config_spec) ``` -------------------------------- ### Working with Items that contain files Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Placeholder for code examples related to handling items with files. ```python item_id = "{item_id}" vault_id = "{vault_id}" ``` -------------------------------- ### Example: Generate Password with GeneratorRecipe Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/types.md An example demonstrating how to use GeneratorRecipe to create a Field object that generates a 16-character password with letters and digits. ```python from onepasswordconnectsdk.models import Field, GeneratorRecipe # Generate 16-character password with letters and digits only field = Field( purpose="PASSWORD", generate=True, recipe=GeneratorRecipe( length=16, character_sets=["LETTERS", "DIGITS"] ) ) ``` -------------------------------- ### NoVaultSetForFieldException Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Raised when no vault is specified for a field in configuration. This example shows how to catch the exception and provides resolutions. ```python from onepasswordconnectsdk.config import load_dict from onepasswordconnectsdk.errors import NoVaultSetForFieldException config = { "api_key": { "opitem": "API Credentials", "opfield": ".api_key" # NOTE: opvault is missing and OP_VAULT not set } } try: secrets = load_dict(client, config) except NoVaultSetForFieldException as e: print(f"Config error: {e}") ``` -------------------------------- ### Advanced Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Example of advanced usage with custom client configuration, including a CA file. ```python # For custom configuration from onepasswordconnectsdk.client import Client from onepasswordconnectsdk.config import ClientConfig config = ClientConfig(ca_file="/path/to/ca.crt") client = Client("https://connect.example.com", "token", config=config) ``` -------------------------------- ### Initialize Client from Environment Variables Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Demonstrates how to create a client by reading configuration from environment variables, with options to override. ```python from onepasswordconnectsdk.client import new_client_from_environment # Uses environment variables client = new_client_from_environment() # Or override with parameters client = new_client_from_environment( url="http://custom-host:8080", token="custom_token" ) ``` -------------------------------- ### PathBuilder - files (no uuid) Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example of appending the /files segment to a path. ```python # "/v1/vaults/vault_uuid/items/item_uuid/files" path1 = PathBuilder().vaults("vault_uuid").items("item_uuid").files().build() ``` -------------------------------- ### Get Item by Title Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves an item from a vault by its exact title. ```python item = client.get_item_by_title("Database Password", "vault_uuid") ``` -------------------------------- ### Working with Vaults Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Code examples for retrieving a list of all vaults and fetching a specific vault by its ID or title. ```python # Get a list of all vaults vaults = connect_client.get_vaults() # Get a specific vault vault = connect_client.get_vault("{vault_id}") vault_by_title = connect_client.get_vault_by_title("{vault_title}") ``` -------------------------------- ### PathBuilder - content Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example of appending the /content segment to a path for accessing file content. ```python # "/v1/vaults/vault_uuid/items/item_uuid/files/file_uuid/content" path = PathBuilder().vaults("vault_uuid").items("item_uuid").files("file_uuid").content().build() ``` -------------------------------- ### PathBuilder - files (with uuid) Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example of appending the /files segment with a specific file UUID to a path. ```python # "/v1/vaults/vault_uuid/items/item_uuid/files/file_uuid" path2 = PathBuilder().vaults("vault_uuid").items("item_uuid").files("file_uuid").build() ``` -------------------------------- ### Client Initialization Error - EnvironmentHostNotSetException Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Example of catching an exception when the Connect API host URL is not provided. ```python # If OP_CONNECT_HOST is not set: from onepasswordconnectsdk.client import new_client_from_environment try: client = new_client_from_environment() except EnvironmentHostNotSetException as e: print(f"Missing host: {e}") # Set OP_CONNECT_HOST and try again ``` -------------------------------- ### Create Item Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/README.md Provides an example of creating a new item with a title, category, vault reference, and fields, then sending it to the API. ```python from onepasswordconnectsdk.models import Item, ItemVault, Field item = Item( title="My Secret", category="LOGIN", vault=ItemVault(id="vault_uuid"), fields=[Field(value="secret", purpose="PASSWORD")] ) created = client.create_item("vault_uuid", item) ``` -------------------------------- ### PathBuilder - query Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Example of adding a query string parameter to a path. Note that spaces must be encoded by the caller if needed. ```python # "/v1/vaults/vault_uuid/items?filter=title%20eq%20%22My%20Item%22" # (note: spaces must be encoded by caller if needed) path = PathBuilder().vaults("vault_uuid").items().query("filter", 'title eq "My Item"').build() ``` -------------------------------- ### Client Initialization Error - EnvironmentTokenNotSetException Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Example of catching an exception when the Service Account token is not provided. ```python # If OP_CONNECT_TOKEN is not set: from onepasswordconnectsdk.client import new_client_from_environment try: client = new_client_from_environment() except EnvironmentTokenNotSetException as e: print(f"Missing token: {e}") ``` -------------------------------- ### UnknownSectionAndFieldTag Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Demonstrates how to catch an UnknownSectionAndFieldTag when a specified section or field does not exist in a 1Password item. ```python from onepasswordconnectsdk.config import load_dict config = { "password": { "opitem": "Database", "opfield": "nonexistent_section.field", # Section doesn't exist "opvault": "vault_id" } } try: secrets = load_dict(client, config) except UnknownSectionAndFieldTag as e: print(f"Section or field not found: {e}") ``` -------------------------------- ### Recommended Error Handling Pattern Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md A comprehensive example of error handling for common exceptions when interacting with the 1Password Connect SDK. ```python from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.errors import ( OnePasswordConnectSDKError, FailedToRetrieveItemException, FailedToRetrieveVaultException ) try: client = new_client_from_environment() except (EnvironmentHostNotSetException, EnvironmentTokenNotSetException) as e: print(f"Configuration error: {e}") exit(1) try: item = client.get_item_by_id("item_uuid", "vault_uuid") except FailedToRetrieveItemException as e: print(f"Item retrieval failed: {e}") if hasattr(e, 'status_code'): if e.status_code == 404: print("Item not found") elif e.status_code >= 500: print("Server error - try again later") except FailedToRetrieveVaultException as e: print(f"Vault error: {e}") except OnePasswordConnectSDKError as e: print(f"Unexpected SDK error: {e}") ``` -------------------------------- ### Disable Timeout Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Example of disabling the client request timeout by setting the OP_CONNECT_CLIENT_REQ_TIMEOUT environment variable to None. ```bash export OP_CONNECT_CLIENT_REQ_TIMEOUT=None python app.py ``` -------------------------------- ### Get Item by ID Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Retrieves a specific item from a vault using its UUID. ```python item = await client.get_item_by_id("item_uuid_26chars", "vault_uuid_26chars") print(item.title) ``` -------------------------------- ### Update Item Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/async-client.md Updates an existing item in a vault. The method automatically sets the item's ID and vault reference. ```python item = await client.get_item_by_id(item_id, vault_id) item.title = "Updated Title" item.fields[0].value = "new_password" updated = await client.update_item(item_id, vault_id, item) ``` -------------------------------- ### Creating a Connect API Client Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Demonstrates how to create a client instance using environment variables or by providing the Connect host and API token. Also shows how to create an asynchronous client. ```python from onepasswordconnectsdk.client import ( Client, new_client_from_environment, new_client ) # creating client using OP_CONNECT_TOKEN and OP_CONNECT_HOST environment variables connect_client_from_env: Client = new_client_from_environment() # creates a client by supplying hostname and 1Password Connect API token connect_client_from_token: Client = new_client( "{1Password_Connect_Host}", "{1Password_Connect_API_Token}" ) # creates async client connect_async_client: Client = new_client( "{1Password_Connect_Host}", "{1Password_Connect_API_Token}", True ) ``` -------------------------------- ### PathBuilder Initialization Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Creates a new path builder starting with the specified API version. The builder uses a fluent interface to incrementally construct request paths. ```python from onepasswordconnectsdk.utils import PathBuilder # Builds path "/v1/vaults/vault_uuid/items/item_uuid" path = PathBuilder().vaults("vault_uuid").items("item_uuid").build() ``` -------------------------------- ### Async Client Configuration Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Demonstrates that the same configuration options apply to both synchronous and asynchronous clients. ```python config = ClientConfig( ca_file="path/to/ca.pem", timeout=30.0 ) async_client = new_client("https://connect.example.com", "your-token", is_async=True, config=config) ``` -------------------------------- ### Synchronous Client (Basic) Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/README.md Demonstrates how to initialize a synchronous client from environment variables and retrieve a vault and an item. ```python from onepasswordconnectsdk.client import new_client_from_environment client = new_client_from_environment() vault = client.get_vault("vault_uuid") item = client.get_item("item_uuid", "vault_uuid") ``` -------------------------------- ### Additional Configuration Options Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Illustrates how to configure timeouts, redirects, proxy settings, and custom headers using the ClientConfig class. ```python # Configure timeouts and redirects config = ClientConfig( ca_file="path/to/ca.pem", timeout=30.0, # 30 second timeout follow_redirects=True, # Follow HTTP redirects max_redirects=5 # Maximum number of redirects to follow ) # Configure proxy settings config = ClientConfig( proxies={ "http://": "http://proxy.example.com", "https://": "https://proxy.example.com" } ) # Configure custom headers config = ClientConfig( headers={ "User-Agent": "CustomApp/1.0", "X-Custom-Header": "value" } ) ``` -------------------------------- ### InvalidFieldPathException Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Raised when the field path format is invalid. This example shows how to catch the exception. ```python from onepasswordconnectsdk.config import load_dict config = { "password": { "opitem": "Database", "opfield": "invalid_path_without_dot", # Missing dot "opvault": "vault_id" } } try: secrets = load_dict(client, config) except InvalidFieldPathException as e: print(f"Invalid field path: {e}") ``` -------------------------------- ### NoFieldTagSetForFieldException Example Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Raised when the required `opfield` tag is missing from a field specification. This example shows how to catch the exception. ```python from onepasswordconnectsdk.config import load_dict config = { "password": { "opitem": "Database", # NOTE: opfield is missing } } try: secrets = load_dict(client, config) except NoFieldTagSetForFieldException as e: print(f"Missing field specification: {e}") ``` -------------------------------- ### Client Class Initialization Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Initializes a new synchronous client instance. Creates an httpx.Client session with provided credentials and configuration. ```python from onepasswordconnectsdk.client import Client client = Client( url="http://localhost:8080", token="my_service_account_token" ) ``` -------------------------------- ### get_timeout Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/utils.md Get HTTP request timeout configuration from environment. ```bash # Use default httpx timeout unset OP_CONNECT_CLIENT_REQ_TIMEOUT # Set 30-second timeout export OP_CONNECT_CLIENT_REQ_TIMEOUT=30 # Disable timeouts export OP_CONNECT_CLIENT_REQ_TIMEOUT=None ``` -------------------------------- ### Get Item by ID Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves a specific item from a vault using its UUID. ```python item = client.get_item_by_id("item_uuid_26chars", "vault_uuid_26chars") print(item.title) print(item.fields) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/1password/connect-sdk-python/blob/main/README.md Set the necessary environment variables for the Connect server host and authentication token. ```sh export OP_CONNECT_HOST= && \ export OP_CONNECT_TOKEN= ``` ```sh # set the timeout to 90 seconds export OP_CONNECT_CLIENT_REQ_TIMEOUT=90 ``` -------------------------------- ### Get Items Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves all items within a vault, with an option to filter them using a query. ```python # Get all items all_items = client.get_items("vault_uuid") # Get filtered items filtered = client.get_items("vault_uuid", 'title eq "Login"') for item in filtered: print(item.title) ``` -------------------------------- ### Basic Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Recommended import pattern for basic usage of the 1Password Connect SDK. ```python # Recommended: Use top-level imports from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.models import Item, Field client = new_client_from_environment() item = client.get_item("item_uuid", "vault_uuid") ``` -------------------------------- ### OP_CONNECT_CLIENT_ASYNC Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Usage of OP_CONNECT_CLIENT_ASYNC when creating an async client from environment variables. ```python import asyncio from onepasswordconnectsdk.client import new_client_from_environment async def main(): # Returns AsyncClient when OP_CONNECT_CLIENT_ASYNC=True client = new_client_from_environment() vault = await client.get_vault("vault_uuid") await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### Asynchronous Client Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/README.md Shows how to set up and use an asynchronous client, including retrieving a vault and an item, and properly closing the client. ```python import asyncio from onepasswordconnectsdk.client import new_client async def main(): client = new_client("http://localhost:8080", "token", is_async=True) vault = await client.get_vault("vault_uuid") item = await client.get_item("item_uuid", "vault_uuid") await client.__aexit__() asyncio.run(main()) ``` -------------------------------- ### Custom Configuration Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/README.md Illustrates creating a client with custom configuration, such as specifying a CA file and a request timeout. ```python from onepasswordconnectsdk.config import ClientConfig from onepasswordconnectsdk.client import new_client config = ClientConfig(ca_file="/path/to/ca.crt", timeout=30) client = new_client("https://connect.example.com", "token", config=config) vault = client.get_vault("vault_uuid") ``` -------------------------------- ### Read a Secret Source: https://github.com/1password/connect-sdk-python/blob/main/README.md Initialize the client from environment variables and retrieve an item from a vault. ```python from onepasswordconnectsdk.client import ( Client, new_client_from_environment, ) connect_client: Client = new_client_from_environment() client.get_item("{item_id}", "{vault_id}") ``` -------------------------------- ### OP_CONNECT_HOST Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Usage of OP_CONNECT_HOST when creating a client from environment variables. ```python from onepasswordconnectsdk.client import new_client_from_environment # Uses OP_CONNECT_HOST automatically client = new_client_from_environment() ``` -------------------------------- ### OP_CONNECT_TOKEN Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Usage of OP_CONNECT_TOKEN when creating a client from environment variables. ```python from onepasswordconnectsdk.client import new_client_from_environment # Uses OP_CONNECT_TOKEN automatically client = new_client_from_environment() ``` -------------------------------- ### Model Serialization Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Demonstrates creating a model instance and converting it to a dictionary, and how models serialize automatically when sent to the API. ```python from onepasswordconnectsdk.models import Item, Field # Create model item = Item( title="My Item", category="LOGIN", fields=[Field(value="secret")] ) # Convert to dictionary item_dict = item.to_dict() # Models serialize automatically when sent to API created_item = client.create_item("vault_uuid", item) ``` -------------------------------- ### Load Configuration Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/README.md Demonstrates loading secrets from a dictionary configuration using the SDK, specifying item, field, and vault details. ```python from onepasswordconnectsdk.client import new_client_from_environment from onepasswordconnectsdk.config import load_dict client = new_client_from_environment() config = { "db_password": { "opitem": "Database", "opfield": "credentials.password", "opvault": "vault_uuid" } } secrets = load_dict(client, config) print(secrets["db_password"]) ``` -------------------------------- ### OP_CONNECT_CLIENT_REQ_TIMEOUT Usage Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Usage of OP_CONNECT_CLIENT_REQ_TIMEOUT when creating a client from environment variables. ```python from onepasswordconnectsdk.client import new_client_from_environment # Timeout is read from OP_CONNECT_CLIENT_REQ_TIMEOUT client = new_client_from_environment() ``` -------------------------------- ### Skip SSL Verification (not recommended) Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Configure the client to skip SSL certificate verification. This is not recommended for production environments due to security risks. ```python from onepasswordconnectsdk.config import ClientConfig from onepasswordconnectsdk.client import new_client config = ClientConfig(verify=False) client = new_client("https://connect.example.com", "token", config=config) ``` -------------------------------- ### Default Behavior - Timeout Configuration Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/configuration.md Illustrates the default request timeout behavior when no explicit timeout is set, relying on httpx defaults. ```bash # No explicit timeout set - uses httpx defaults (5 seconds) python app.py ``` -------------------------------- ### Data Retrieval Error - FailedToRetrieveVaultException Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Example of catching an exception when an HTTP error occurs while retrieving vault information. ```python from onepasswordconnectsdk.errors import FailedToRetrieveVaultException try: vault = client.get_vault("invalid_uuid") except FailedToRetrieveVaultException as e: print(f"Cannot retrieve vault: {e}") ``` -------------------------------- ### Data Retrieval Error - FailedToRetrieveItemException Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/errors.md Example of catching an exception when an HTTP error occurs while retrieving or manipulating items. ```python from onepasswordconnectsdk.errors import FailedToRetrieveItemException try: item = client.get_item_by_id("nonexistent_id", "vault_uuid") except FailedToRetrieveItemException as e: print(f"Error: {e}") if hasattr(e, 'status_code') and e.status_code == 404: print("Item not found") else: print("Network or server error") ``` -------------------------------- ### Get Item by ID or Title Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Retrieves an item by its ID or title within a specified vault. Demonstrates retrieval using UUIDs, vault names, and a mix of both. ```python # By UUID item = client.get_item("item_uuid", "vault_uuid") # By title and vault name item = client.get_item("My Login", "Personal") # Mixed item = client.get_item("My Login", "vault_uuid") ``` -------------------------------- ### SSL Certificate Verification Source: https://github.com/1password/connect-sdk-python/blob/main/USAGE.md Shows how to configure SSL certificate verification using a custom CA certificate or by disabling verification (not recommended for production). ```python from onepasswordconnectsdk.config import ClientConfig # Verify SSL using a custom CA certificate config = ClientConfig(ca_file="path/to/ca.pem") client = new_client("https://connect.example.com", "your-token", config=config) # Disable SSL verification (not recommended for production) config = ClientConfig(verify=False) client = new_client("https://connect.example.com", "your-token", config=config) ``` -------------------------------- ### Package Structure Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/modules.md Directory structure of the onepasswordconnectsdk package. ```tree onepasswordconnectsdk/ ├── __init__.py # Top-level exports ├── client.py # Synchronous Client and factory functions ├── async_client.py # AsyncClient implementation ├── config.py # Configuration classes and loaders ├── errors.py # Custom exception classes ├── utils.py # Utility functions and PathBuilder ├── serializer.py # JSON serialization/deserialization ├── connect.py # (empty stub) ├── models/ │ ├── __init__.py # Model imports and exports │ ├── item.py # Item model │ ├── summary_item.py # SummaryItem model │ ├── vault.py # Vault model │ ├── field.py # Field model │ ├── section.py # Section model │ ├── field_section.py # FieldSection model │ ├── file.py # File model │ ├── item_vault.py # ItemVault model │ ├── item_urls.py # ItemUrls model │ ├── item_details.py # ItemDetails model │ ├── generator_recipe.py # GeneratorRecipe model │ ├── error.py # Error model │ ├── parsed_field.py # ParsedField dataclass │ ├── parsed_item.py # ParsedItem dataclass │ └── constants.py # Environment variable names ``` -------------------------------- ### Create Item Source: https://github.com/1password/connect-sdk-python/blob/main/_autodocs/api-reference/client.md Creates a new item in a specified vault. Requires an Item object with details like title, category, vault, and fields. ```python from onepasswordconnectsdk.models import Item, ItemVault, Field new_item = Item( title="My Secret", category="LOGIN", vault=ItemVault(id="vault_uuid"), tags=["important"], fields=[ Field(value="secret_value", purpose="PASSWORD") ] ) created = client.create_item("vault_uuid", new_item) print(created.id) ```