### Complete Desktop App Setup Example Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md An example demonstrating how to set up and use the 1Password client with desktop app authentication. It retrieves a secret after user approval in the desktop application. ```python import asyncio from onepassword import Client, DesktopAuth async def main(): # Get account name from environment or prompt user account_name = "My 1Password Account" # Authenticate with desktop app client = await Client.authenticate( auth=DesktopAuth(account_name=account_name), integration_name="My Desktop App", integration_version="v1.0.0" ) # Use client (requires user approval in desktop app) value = await client.secrets.resolve("op://vault/item/field") print(f"Retrieved secret: {value}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complete Service Account Setup Example Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md An example demonstrating how to set up and use the 1Password client with service account authentication. It retrieves the token from environment variables and lists vaults. ```python import asyncio import os from onepassword import Client, ItemCategory async def main(): # Get token from environment token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") if not token: raise ValueError("OP_SERVICE_ACCOUNT_TOKEN not set") # Authenticate client = await Client.authenticate( auth=token, integration_name="My Python App", integration_version="v1.0.0" ) # Use client vaults = await client.vaults.list() for vault in vaults: print(f"{vault.title} ({vault.id})") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Execute Example Script Source: https://github.com/1password/onepassword-sdk-python/blob/main/example/README.md Run the provided example script from the project root directory. ```bash python example/example.py ``` -------------------------------- ### Install Release Dependencies Source: https://github.com/1password/onepassword-sdk-python/blob/main/src/release/README.md Run this make command to install all dependencies required for the Python SDK release process. ```bash make release/install-dependencies ``` -------------------------------- ### Install 1Password Python SDK Source: https://github.com/1password/onepassword-sdk-python/blob/main/README.md Install the 1Password Python SDK using pip. This is the first step to using the SDK in your project. ```bash pip install onepassword-sdk ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/1password/onepassword-sdk-python/blob/main/example/README.md Set the required service account token and vault UUID environment variables before running the SDK examples. ```bash export OP_SERVICE_ACCOUNT_TOKEN="" ``` ```bash export OP_VAULT_ID="" ``` -------------------------------- ### Get Item Sharing Policy and Create Share Link Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Shows how to retrieve an item's sharing policy and then create a share link for that item. ```python async def main(): client = await Client.authenticate(...) # Get item sharing policy policy = await client.items.shares.get_account_policy(vault_id, item_id) # Create a share link link = await client.items.shares.create(item, policy, share_params) ``` -------------------------------- ### Authenticate with 1Password Desktop App Source: https://github.com/1password/onepassword-sdk-python/blob/main/README.md Example of authenticating with the 1Password SDK using the desktop app. Replace placeholders with your account name and integration details. This method is suitable for local integrations requiring user approval. ```python import asyncio import os from onepassword.client import Client, DesktopAuth async def main(): # Connects to 1Password. Fill in your own integration name and version. client = await Client.authenticate( auth=DesktopAuth( # TODO: Set to your 1Password account name. account_name="your-account-name" ), # TODO: Set to your own integration name and version. integration_name="My 1Password Integration", integration_version="v1.0.0", ) # Retrieves a secret from 1Password. Takes a secret reference as input and returns the secret to which it points. value = await client.secrets.resolve("op://vault/item/field") # use value here if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Get Vault Overview Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/vaults.md Fetches a lightweight overview of a specific vault using its ID. This provides basic information such as title, type, item count, and creation date. ```python async def main(): client = await Client.authenticate(...) vault = await client.vaults.get_overview(vault_id) print(f"Vault: {vault.title}") print(f"Type: {vault.vault_type}") print(f"Items: {vault.active_item_count}") print(f"Created: {vault.created_at}") ``` -------------------------------- ### Authenticate with Desktop App Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md Ideal for local development or user-facing applications requiring human approval. Requires the 1Password desktop app to be installed and configured for SDK integration. ```python import asyncio from onepassword import Client, DesktopAuth async def main(): client = await Client.authenticate( auth=DesktopAuth(account_name="My Account Name"), integration_name="My Integration", integration_version="v1.0.0" ) ``` -------------------------------- ### Prepare for Release Source: https://github.com/1password/onepassword-sdk-python/blob/main/src/release/README.md Navigate to the root of the repository and execute this command to prepare for the release. Follow the script's instructions. ```bash make prep-release ``` -------------------------------- ### Get a Specific Group Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/client.md Accesses the groups API to retrieve details for a specific group by its ID and optional parameters. ```python group = await client.groups.get(group_id, GroupGetParams()) ``` -------------------------------- ### Client Initialization with Weakref Finalizer Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md Demonstrates how the SDK uses Python's `weakref.finalize` to automatically manage client lifecycle and free native SDK core memory when the Client object is garbage collected. ```python authenticated_client._finalizer = weakref.finalize( cls, core.release_client, client_id ) ``` -------------------------------- ### Build Wheels and Source Distribution Source: https://github.com/1password/onepassword-sdk-python/blob/main/src/release/README.md Build the wheels and source distribution for PyPI by running this command in the root of the repository. ```bash make build-wheels ``` -------------------------------- ### Get All Items from Vault Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Retrieves all items from a specified vault, optionally filtering by a list of item IDs. Handles potential errors during retrieval for individual items. ```python async def main(): client = await Client.authenticate(...) response = await client.items.get_all( vault_id, ["item_id_1", "item_id_2", "item_id_3"] ) for result in response.individual_responses: if result.error: print(f"Failed to retrieve item: {result.error}") else: print(f"Retrieved item {result.content.id}: {result.content.title}") ``` -------------------------------- ### Get 1Password Account Sharing Policy Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-shares.md Retrieves the item sharing policy configured for your 1Password account. Use this to understand sharing limitations before creating shares. ```python async def main(): client = await Client.authenticate(...) policy = await client.items.shares.get_account_policy(vault_id, item_id) print(f"Max expiry: {policy.max_expiry}") print(f"Default expiry: {policy.default_expiry}") print(f"Max views: {policy.max_views}") print(f"Allowed types: {policy.allowed_types}") print(f"Allowed recipient types: {policy.allowed_recipient_types}") ``` -------------------------------- ### Execute Release Process Source: https://github.com/1password/onepassword-sdk-python/blob/main/src/release/README.md Once all checks are complete and everything looks good, run this command at the root of the repository to execute the release process. ```bash make release ``` -------------------------------- ### Attach File to Item and Read File Content Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Illustrates how to attach a file to an existing item and how to read the content of an item's file. ```python async def main(): client = await Client.authenticate(...) # Attach a file to an item updated_item = await client.items.files.attach(item, file_params) # Read file content content = await client.items.files.read(vault_id, item_id, file_attributes) ``` -------------------------------- ### List and Filter Items Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Demonstrates how to list all active items in a vault and how to specifically list archived items using filters. ```python from onepassword import ItemListFilterByState, ItemListFilterByStateInner async def main(): client = await Client.authenticate(...) # List all active items all_items = await client.items.list(vault_id) for overview in all_items: print(f"{overview.title} ({overview.id})") # List archived items only archived = await client.items.list( vault_id, ItemListFilterByState( content=ItemListFilterByStateInner(active=False, archived=True) ) ) for overview in archived: print(f"Archived: {overview.title}") ``` -------------------------------- ### Get Detailed Vault Information Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/vaults.md Retrieves detailed information about a vault, including optional access information if the accessors flag is set to True in VaultGetParams. Use this when you need comprehensive vault details. ```python from onepassword import VaultGetParams async def main(): client = await Client.authenticate(...) vault = await client.vaults.get( vault_id, VaultGetParams(accessors=True) ) print(f"Vault: {vault.title}") if vault.access: for access in vault.access: print(f"Access: {access.accessor_type} {access.accessor_uuid} - {access.permissions}") ``` -------------------------------- ### Initialize DesktopAuth Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md Used to create an instance for desktop app authentication. Specify your 1Password account name as displayed in the desktop app. ```python from onepassword import DesktopAuth auth = DesktopAuth(account_name="John Doe") client = await Client.authenticate( auth=auth, integration_name="My App", integration_version="v1.0.0" ) ``` -------------------------------- ### Get Group Information Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/groups.md Retrieves a group's details, with an option to include vault permissions. Use this to fetch specific group data for display or further processing. Ensure the client is authenticated before making the call. ```python from onepassword import GroupGetParams async def main(): client = await Client.authenticate(...) # Get group without vault permissions group = await client.groups.get( group_id, GroupGetParams(vaultPermissions=False) ) print(f"Group: {group.title}") print(f"Type: {group.group_type}") print(f"State: {group.state}") print(f"Description: {group.description}") # Get group with vault permissions group_with_access = await client.groups.get( group_id, GroupGetParams(vaultPermissions=True) ) if group_with_access.vault_access: for access in group_with_access.vault_access: print(f"Vault {access.vault_uuid}: permissions={access.permissions}") ``` -------------------------------- ### Authenticate 1Password Client with Environment Variables Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md Use this snippet to authenticate the 1Password client by checking for the OP_SERVICE_ACCOUNT_TOKEN environment variable. If present, it uses service account authentication; otherwise, it falls back to desktop app authentication using OP_ACCOUNT_NAME. Ensure the necessary environment variables are set before running. ```python import asyncio import os from onepassword import Client, DesktopAuth async def main(): # Check if using service account or desktop app token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") if token: # Service account authentication auth = token print("Using service account authentication") else: # Desktop app authentication account_name = os.getenv("OP_ACCOUNT_NAME", "My Account") auth = DesktopAuth(account_name=account_name) print(f"Using desktop app authentication ({account_name})") client = await Client.authenticate( auth=auth, integration_name=os.getenv("INTEGRATION_NAME", "My App"), integration_version=os.getenv("INTEGRATION_VERSION", "v1.0.0") ) # Use client... if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Authenticate and Retrieve Secret using Python SDK Source: https://github.com/1password/onepassword-sdk-python/blob/main/README.md Demonstrates how to authenticate with the 1Password SDK using a service account token from an environment variable and retrieve a secret using its reference. ```python import asyncio import os from onepassword.client import Client async def main(): # Gets your service account token from the OP_SERVICE_ACCOUNT_TOKEN environment variable. token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") # Connects to 1Password. Fill in your own integration name and version. client = await Client.authenticate(auth=token, integration_name="My 1Password Integration", integration_version="v1.0.0") # Retrieves a secret from 1Password. Takes a secret reference as input and returns the secret to which it points. value = await client.secrets.resolve("op://vault/item/field") # use value here if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Client Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/INDEX.md The main entry point for the SDK. It provides methods for authentication and access to other API resources like Secrets, Items, Vaults, and Groups. ```APIDOC ## Client ### Description Provides the main entry point for the SDK, including authentication and access to various API resources. ### Methods - `authenticate()`: Class method for SDK authentication. ### Properties - `secrets`: Access to Secrets API. - `items`: Access to Items API. - `vaults`: Access to Vaults API. - `groups`: Access to Groups API. ``` -------------------------------- ### Unsupported Architecture Error Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md This error is raised when the SDK binary is run on an unsupported machine architecture. ```python ImportError: Your machine's architecture is not currently supported: ``` -------------------------------- ### Client.authenticate Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/client.md Creates and returns an authenticated client instance for interacting with the 1Password API. Supports both service account token and desktop app authentication. ```APIDOC ## Client.authenticate ### Description Creates and returns an authenticated client instance. ### Method `classmethod async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **auth** (`str | DesktopAuth`) - Required - Either a service account token string or a DesktopAuth instance for 1Password desktop app authentication - **integration_name** (`str`) - Required - The name of your integration (e.g., "My 1Password Integration") - **integration_version** (`str`) - Required - The version of your integration (e.g., "v1.0.0") ### Return Type `Client` — An authenticated client instance with access to secrets, items, vaults, and groups APIs. ### Throws - `Exception` — If authentication fails or invalid parameters are provided - `DesktopSessionExpiredException` — If desktop app authentication session expires ### Example Service account authentication: ```python import asyncio import os from onepassword import Client async def main(): token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") client = await Client.authenticate( auth=token, integration_name="My 1Password Integration", integration_version="v1.0.0" ) # Use client.secrets, client.items, etc. value = await client.secrets.resolve("op://vault/item/field") ``` Desktop app authentication: ```python import asyncio from onepassword import Client, DesktopAuth async def main(): client = await Client.authenticate( auth=DesktopAuth(account_name="My Account"), integration_name="My 1Password Integration", integration_version="v1.0.0" ) # Use client APIs value = await client.secrets.resolve("op://vault/item/field") ``` ``` -------------------------------- ### VaultOverview Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md A lightweight summary of a vault. ```APIDOC ## VaultOverview ### Description Lightweight summary of a vault. ### Fields - **id** (string) - Yes - The vault's unique identifier - **title** (string) - Yes - The vault's title - **description** (string) - Yes - The vault's description - **vault_type** (VaultType) - Yes - The vault's type - **active_item_count** (integer) - Yes - Number of active items - **content_version** (integer) - Yes - Content version - **attribute_version** (integer) - Yes - Attribute version - **created_at** (datetime) - Yes - Creation timestamp - **updated_at** (datetime) - Yes - Last update timestamp ``` -------------------------------- ### Items.shares.create Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Creates a share link for an item based on the provided item, policy, and share parameters. ```APIDOC ## Items.shares.create ### Description Creates a share link for an item based on the provided item, policy, and share parameters. ### Method `create(item, policy, share_params)` ### Parameters #### Request Body - **item** (object) - Required - The item object to share. - **policy** (object) - Required - The sharing policy to apply. - **share_params** (object) - Required - Parameters for creating the share link. ### Response #### Success Response - Returns the created share link object. #### Response Example ```json { "share_link": "https://..." } ``` ``` -------------------------------- ### Items.create_all Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Creates multiple items in a single vault in batch. This is useful for efficiently adding several items at once. ```APIDOC ## Items.create_all ### Description Creates multiple items in a single vault in batch. ### Method `async def create_all(self, vault_id: str, params: List[ItemCreateParams]) -> ItemsUpdateAllResponse` ### Parameters #### Path Parameters - **vault_id** (`str`) - Required - The ID of the vault where items will be created #### Request Body - **params** (`List[ItemCreateParams]`) - Required - List of ItemCreateParams objects for items to create ### Return Type `ItemsUpdateAllResponse` — Response object containing a list of individual responses with content (Item) or error (ItemUpdateFailureReason) ### Example ```python async def main(): client = await Client.authenticate(...) items_to_create = [ ItemCreateParams( title="Login 1", category=ItemCategory.LOGIN, vault_id=vault_id, fields=[...] ), ItemCreateParams( title="Login 2", category=ItemCategory.LOGIN, vault_id=vault_id, fields=[...] ) ] response = await client.items.create_all(vault_id, items_to_create) for result in response.individual_responses: if result.error: print(f"Failed to create item: {result.error}") else: print(f"Created item {result.content.id}") ``` ``` -------------------------------- ### Authenticate Client with Desktop App Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/client.md Authenticates the client using the 1Password desktop application. Requires a DesktopAuth instance specifying the account name. ```python import asyncio from onepassword import Client, DesktopAuth async def main(): client = await Client.authenticate( auth=DesktopAuth(account_name="My Account"), integration_name="My 1Password Integration", integration_version="v1.0.0" ) # Use client APIs value = await client.secrets.resolve("op://vault/item/field") ``` -------------------------------- ### Default SDK Constants Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md The SDK defines default values for integration name, version, request library, and OS version. ```python DEFAULT_INTEGRATION_NAME = "Unknown" DEFAULT_INTEGRATION_VERSION = "Unknown" DEFAULT_REQUEST_LIBRARY = "reqwest" DEFAULT_REQUEST_LIBRARY_VERSION = "0.11.24" DEFAULT_OS_VERSION = "0.0.0" SDK_LANGUAGE = "Python" SDK_VERSION = SDK_BUILD_NUMBER # From build_number.py ``` -------------------------------- ### VaultOverview Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md A lightweight model for summarizing vault information. Useful for listing vaults without full details. ```python class VaultOverview(BaseModel): id: str title: str description: str vault_type: VaultType # alias: vaultType active_item_count: int # alias: activeItemCount content_version: int # alias: contentVersion attribute_version: int # alias: attributeVersion created_at: datetime # alias: createdAt updated_at: datetime # alias: updatedAt ``` -------------------------------- ### Create Multiple Items in Batch Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Efficiently create multiple items within the same vault using a list of ItemCreateParams. Handles individual item creation results, including errors. ```Python async def main(): client = await Client.authenticate(...) items_to_create = [ ItemCreateParams( title="Login 1", category=ItemCategory.LOGIN, vault_id=vault_id, fields=[...] ), ItemCreateParams( title="Login 2", category=ItemCategory.LOGIN, vault_id=vault_id, fields=[...] ) ] response = await client.items.create_all(vault_id, items_to_create) for result in response.individual_responses: if result.error: print(f"Failed to create item: {result.error}") else: print(f"Created item {result.content.id}") ``` -------------------------------- ### Website Data Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Stores website information for autofill purposes, including the URL, a label, and the autofill behavior. ```python class Website(BaseModel): url: str label: str autofill_behavior: AutofillBehavior # alias: autofillBehavior ``` -------------------------------- ### Authenticate Client with Service Account Token Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/client.md Authenticates the client using a service account token. Ensure the OP_SERVICE_ACCOUNT_TOKEN environment variable is set. ```python import asyncio import os from onepassword import Client async def main(): token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") client = await Client.authenticate( auth=token, integration_name="My 1Password Integration", integration_version="v1.0.0" ) # Use client.secrets, client.items, etc. value = await client.secrets.resolve("op://vault/item/field") ``` -------------------------------- ### Implementing Exponential Backoff for Rate Limiting Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/errors.md Use exponential backoff with random jitter to handle `RateLimitExceededException` by waiting an increasing amount of time between retries. ```python import asyncio import random async def api_call_with_backoff(fn, max_retries=3): for attempt in range(max_retries): try: return await fn() except RateLimitExceededException: if attempt == max_retries - 1: raise wait_time = (2 ** attempt) + random.random() await asyncio.sleep(wait_time) ``` -------------------------------- ### Python SDK File Structure Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/INDEX.md This snippet shows the directory structure of the 1Password SDK for Python. It details the purpose of each file within the src/onepassword directory. ```text src/onepassword/ ├── __init__.py # Public exports ├── client.py # Client class ├── core.py # UniffiCore, InnerClient ├── defaults.py # DesktopAuth, configuration ├── errors.py # Exception types ├── secrets.py # Secrets API ├── items.py # Items API ├── items_shares.py # ItemsShares API ├── items_files.py # ItemsFiles API ├── vaults.py # Vaults API ├── groups.py # Groups API └── types.py # All type definitions ``` -------------------------------- ### SDK Configuration Dictionary Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md The SDK generates this configuration dictionary internally. It is sent to the 1Password backend for identification, rate limiting, and usage tracking. ```json { "programmingLanguage": "Python", "sdkVersion": "", "integrationName": "", "integrationVersion": "", "requestLibraryName": "reqwest", "requestLibraryVersion": "0.11.24", "os": "", # "linux", "darwin", "windows" "osVersion": "0.0.0", "architecture": "" # "x86_64", "aarch64", etc. } ``` -------------------------------- ### Vaults.create Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/vaults.md Creates a new vault with a title, optional description, and optional admin access control. ```APIDOC ## Vaults.create ### Description Creates a new vault. This operation allows specifying a title, an optional description, and whether administrators should have access. ### Method `async def create(self, params: VaultCreateParams) -> Vault` ### Parameters #### Path Parameters — #### Query Parameters — #### Request Body - **params** (`VaultCreateParams`) - Required - Parameters object containing title, optional description, and optional allow_admins_access ### Request Example ```python from onepassword import VaultCreateParams async def main(): client = await Client.authenticate(...) vault = await client.vaults.create( VaultCreateParams( title="My Project Vault", description="Secrets for my project", allow_admins_access=False ) ) print(f"Created vault: {vault.id} - {vault.title}") ``` ### Response #### Success Response (200) - **Vault** (`Vault`) - The created vault object with full details including ID, type, and version numbers #### Response Example ```json { "id": "vault_id", "title": "My Project Vault", "description": "Secrets for my project", "allow_admins_access": false, "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:00:00Z", "type": "user", "version": "1" } ``` ### Throws - `Exception` - If vault creation fails ``` -------------------------------- ### Authenticate with Service Account Token Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md Use this method for automated or server-side integrations. Ensure the OP_SERVICE_ACCOUNT_TOKEN environment variable is set. ```python import asyncio import os from onepassword import Client async def main(): # Get service account token from environment token = os.getenv("OP_SERVICE_ACCOUNT_TOKEN") # Create authenticated client client = await Client.authenticate( auth=token, integration_name="My Integration", integration_version="v1.0.0" ) ``` -------------------------------- ### Vaults.get_overview Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/vaults.md Retrieves a lightweight overview of a specific vault using its ID. ```APIDOC ## Vaults.get_overview ### Description Retrieves a lightweight overview of a vault, providing basic information such as title, item count, and creation date. ### Method `async def get_overview(self, vault_id: str) -> VaultOverview` ### Parameters #### Path Parameters - **vault_id** (`str`) - Required - The ID of the vault to retrieve #### Query Parameters — #### Request Body — ### Return Type `VaultOverview` — VaultOverview object with basic vault information ### Example ```python async def main(): client = await Client.authenticate(...) vault = await client.vaults.get_overview(vault_id) print(f"Vault: {vault.title}") print(f"Type: {vault.vault_type}") print(f"Items: {vault.active_item_count}") print(f"Created: {vault.created_at}") ``` ### Response #### Success Response (200) - **VaultOverview** (`VaultOverview`) - VaultOverview object with basic vault information #### Response Example ```json { "id": "vault_id", "title": "My Project Vault", "active_item_count": 5, "type": "user", "version": "1", "created_at": "2023-01-01T12:00:00Z" } ``` ### Throws - `Exception` - If the vault is not found ``` -------------------------------- ### ItemsFiles.attach Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-files.md Attaches a file to an existing item as a file field. It takes the item and file creation parameters, returning the updated item. ```APIDOC ## ItemsFiles.attach ### Description Attaches a file to an existing item as a file field. ### Method `attach` ### Parameters #### Path Parameters - **item** (Item) - Required - The Item object to attach the file to - **file_params** (FileCreateParams) - Required - Parameters containing file name, content, section ID, and field ID ### Return Type `Item` — The updated item with the attached file ### Throws - `Exception` — If file attachment fails due to size limits or validation errors ### Example ```python from onepassword import FileCreateParams async def main(): client = await Client.authenticate(...) item = await client.items.get(vault_id, item_id) file_content = b"file content here" updated_item = await client.items.files.attach( item, FileCreateParams( name="document.pdf", content=file_content, sectionId="", fieldId="my_file_field" ) ) print(f"Attached file to item {updated_item.id}") ``` ``` -------------------------------- ### Items.files.attach Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Attaches a file to an existing item. ```APIDOC ## Items.files.attach ### Description Attaches a file to an existing item. ### Method `attach(item, file_params)` ### Parameters #### Request Body - **item** (object) - Required - The item to which the file will be attached. - **file_params** (object) - Required - Parameters defining the file to attach. ### Response #### Success Response - Returns the updated item object with the file attached. #### Response Example ```json { "id": "item_id", "title": "Updated Item", "files": [ { "id": "file_id", "name": "example.txt" } ] } ``` ``` -------------------------------- ### AutofillBehavior Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Enumeration of autofill behaviors that can be applied to items. ```APIDOC ## AutofillBehavior Enumeration of autofill behaviors. ```python class AutofillBehavior(str, Enum): ANYWHEREONWEBSITE = "AnywhereOnWebsite" EXACTDOMAIN = "ExactDomain" NEVER = "Never" ``` ``` -------------------------------- ### VaultCreateParams Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the parameters required for creating a new 1Password vault. Includes title, description, and admin access settings. ```python class VaultCreateParams(BaseModel): title: str description: Optional[str] allow_admins_access: Optional[bool] # alias: allowAdminsAccess ``` -------------------------------- ### DocumentCreateParams Data Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Parameters for creating or replacing a document item's file, including the file name and its content. ```python class DocumentCreateParams(BaseModel): name: str content: bytes ``` -------------------------------- ### FileCreateParams Data Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Parameters for creating or attaching a file, specifying its name, content, and the section and field IDs it belongs to. ```python class FileCreateParams(BaseModel): name: str content: bytes section_id: str # alias: sectionId field_id: str # alias: fieldId ``` -------------------------------- ### Generate a PIN Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/secrets.md Use this snippet to generate a numeric PIN of a specified length. It requires importing the Secrets class and the specific recipe for PIN generation. ```python from onepassword import Secrets, PasswordRecipePin, PasswordRecipePinInner pin = Secrets.generate_password( PasswordRecipePin( parameters=PasswordRecipePinInner(length=6) ) ) print(f"Generated PIN: {pin.password}") ``` -------------------------------- ### Items.get_all Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Retrieves multiple items from a single vault in batch using a list of item IDs. This is an efficient way to fetch several items simultaneously. ```APIDOC ## Items.get_all ### Description Retrieves multiple items from a single vault in batch. ### Method `async def get_all(self, vault_id: str, item_ids: List[str]) -> ItemsGetAllResponse` ### Parameters #### Path Parameters - **vault_id** (`str`) - Required - The ID of the vault containing the items #### Query Parameters - **item_ids** (`List[str]`) - Required - List of item IDs to retrieve ### Return Type `ItemsGetAllResponse` — Response object containing a list of individual responses with content (Item) or error (ItemsGetAllError) ``` -------------------------------- ### ItemsShares.create Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-shares.md Creates a share link for a given item. This operation requires the item, the account's sharing policy, and specific sharing parameters like recipients and expiry settings. ```APIDOC ## ItemsShares.create ### Description Creates a share link for an item with specified recipients and expiry settings. ### Method Asynchronous function call (Python SDK) ### Parameters #### Request Body - **item** (Item) - Required - The Item object to share - **policy** (ItemShareAccountPolicy) - Required - The account sharing policy - **params** (ItemShareParams) - Required - Share parameters including recipients, expiry, and one-time-only setting ### Return Type `str` — The share link URL as a string ### Throws - `Exception` — If the share creation fails due to policy violations or invalid parameters ### Example ```python from onepassword import ItemShareDuration, ItemShareParams async def main(): client = await Client.authenticate(...) # Get the item to share item = await client.items.get(vault_id, item_id) # Get sharing policy policy = await client.items.shares.get_account_policy(vault_id, item_id) # Validate recipients valid_recipients = await client.items.shares.validate_recipients( policy, ["user@example.com"] ) # Create share link share_link = await client.items.shares.create( item, policy, ItemShareParams( recipients=valid_recipients, expireAfter=ItemShareDuration.ONEDAY, oneTimeOnly=False ) ) print(f"Share link: {share_link}") # Share link can be sent to recipients ``` ``` -------------------------------- ### Create a New Vault Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/vaults.md Use this function to create a new vault with a title, optional description, and control over admin access. Ensure you have authenticated the client before calling this method. ```python from onepassword import VaultCreateParams async def main(): client = await Client.authenticate(...) vault = await client.vaults.create( VaultCreateParams( title="My Project Vault", description="Secrets for my project", allow_admins_access=False ) ) print(f"Created vault: {vault.id} - {vault.title}") ``` -------------------------------- ### SDK Configuration with Service Account Token Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/configuration.md For service account authentication, an additional 'serviceAccountToken' field is included in the internal SDK configuration dictionary. ```json { ... "serviceAccountToken": "" } ``` -------------------------------- ### Item Share Parameters Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the parameters for sharing a 1Password item. Specify recipients, expiration duration, and whether the share should be one-time. ```python class ItemShareParams(BaseModel): recipients: Optional[List[ValidRecipient]] expire_after: Optional[ItemShareDuration] # alias: expireAfter one_time_only: bool # alias: oneTimeOnly ``` -------------------------------- ### Handling Desktop Session Expiry Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/errors.md Retry operations after catching `DesktopSessionExpiredException`; the SDK automatically re-initializes the desktop session. ```python async def get_with_reauth(client, vault_id, item_id): try: return await client.items.get(vault_id, item_id) except DesktopSessionExpiredException: # The Client automatically re-initializes the session # Just retry the operation return await client.items.get(vault_id, item_id) ``` -------------------------------- ### VaultCreateParams Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Parameters used for creating a new vault. ```APIDOC ## VaultCreateParams ### Description Parameters for creating a vault. ### Fields - **title** (string) - Yes - The vault's title - **description** (string) - No - The vault's description - **allow_admins_access** (boolean) - No - Whether admins have access ``` -------------------------------- ### Items.list Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Lists items within a specified vault, with support for optional filtering. Returns a list of lightweight item summaries. ```APIDOC ## Items.list ### Description Lists items in a vault with optional filtering. ### Method `GET` (Implied by SDK method signature) ### Endpoint `/vaults/{vault_id}/items` (Implied by SDK method signature) ### Parameters #### Path Parameters - **vault_id** (`str`) - Required - The ID of the vault to list items from #### Query Parameters - **filters** (`ItemListFilter`) - Optional - Optional filter(s) to apply to the listing (supports ItemListFilterByState) ### Return Type `List[ItemOverview]` — List of ItemOverview objects (lightweight item summaries) ``` -------------------------------- ### Retrieve Multiple Items in Batch Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Retrieves a list of items from a specified vault by providing a list of item IDs. Returns a response object containing individual results for each item. ```Python async def main(): client = await Client.authenticate(...) items = await client.items.get_all(vault_id, item_ids) # Process the items from the ItemsGetAllResponse object ``` -------------------------------- ### PIN Password Recipe Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the structure for generating PIN codes. This recipe type is used for creating short, numeric PINs. ```python class PasswordRecipePin(BaseModel): type: Literal["Pin"] parameters: PasswordRecipePinInner ``` -------------------------------- ### ItemsGetAllResponse Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Represents the response from a batch item retrieval operation. It contains a list of individual responses for each item. ```python class ItemsGetAllResponse(BaseModel): individual_responses: List[Response[Item, ItemsGetAllError]] ``` -------------------------------- ### Autofill Behavior Enum Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the possible behaviors for autofill actions on websites. Use this to control how and when the SDK attempts to autofill information. ```python class AutofillBehavior(str, Enum): ANYWHEREONWEBSITE = "AnywhereOnWebsite" EXACTDOMAIN = "ExactDomain" NEVER = "Never" ``` -------------------------------- ### Export Service Account Token (macOS/Linux) Source: https://github.com/1password/onepassword-sdk-python/blob/main/README.md Export your 1Password service account token to the OP_SERVICE_ACCOUNT_TOKEN environment variable on macOS or Linux. ```bash export OP_SERVICE_ACCOUNT_TOKEN= ``` -------------------------------- ### PasswordRecipeRandom Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Parameters for generating a random password. ```APIDOC ## PasswordRecipeRandom Parameters for random password generation. ```python class PasswordRecipeRandom(BaseModel): type: Literal["Random"] parameters: PasswordRecipeRandomInner ``` ``` -------------------------------- ### Random Password Recipe Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the structure for generating random passwords. This recipe type allows for customization of length, digits, and symbols. ```python class PasswordRecipeRandom(BaseModel): type: Literal["Random"] parameters: PasswordRecipeRandomInner ``` -------------------------------- ### General Exception Handling for SDK Operations Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/errors.md Use a try-except block to catch standard Python exceptions like ValueError for operations that do not return structured error types, such as item deletion. ```python async def main(): client = await Client.authenticate(...) try: # Operation that may fail await client.items.delete(vault_id, item_id) except ValueError as e: # Message size exceeds limit (50MB) print(f"Message too large: {e}") except Exception as e: # Other errors print(f"Unexpected error: {e}") ``` -------------------------------- ### ItemsUpdateAllResponse Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md The response structure for batch item creation or update operations, detailing the outcome for each individual item. ```APIDOC ## ItemsUpdateAllResponse ### Description Response from batch item creation or update. ### Fields - **individual_responses** (List[Response[Item, ItemUpdateFailureReason]]) - Yes - A list of individual responses for each item creation or update. ``` -------------------------------- ### Replace Document in Item Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-files.md Replaces the document content of an existing item. Ensure you have authenticated the client and have the vault and item IDs. ```python from onepassword import DocumentCreateParams async def main(): client = await Client.authenticate(...) # Get the document item item = await client.items.get(vault_id, item_id) # Read new document content new_content = b"new document content" # Replace the document updated_item = await client.items.files.replace_document( item, DocumentCreateParams( name="updated_document.pdf", content=new_content ) ) print(f"Replaced document in item {updated_item.id}") ``` -------------------------------- ### Export Service Account Token (Windows) Source: https://github.com/1password/onepassword-sdk-python/blob/main/README.md Export your 1Password service account token to the OP_SERVICE_ACCOUNT_TOKEN environment variable on Windows. ```powershell $Env:OP_SERVICE_ACCOUNT_TOKEN = "" ``` -------------------------------- ### Create Share Link for a 1Password Item Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-shares.md Creates a share link for an item with specified recipients and expiry settings. Ensure recipients are validated against the policy before creating the link. The link can be sent to recipients after creation. ```python from onepassword import ItemShareDuration, ItemShareParams async def main(): client = await Client.authenticate(...) # Get the item to share item = await client.items.get(vault_id, item_id) # Get sharing policy policy = await client.items.shares.get_account_policy(vault_id, item_id) # Validate recipients valid_recipients = await client.items.shares.validate_recipients( policy, ["user@example.com"] ) # Create share link share_link = await client.items.shares.create( item, policy, ItemShareParams( recipients=valid_recipients, expireAfter=ItemShareDuration.ONEDAY, oneTimeOnly=False ) ) print(f"Share link: {share_link}") # Share link can be sent to recipients ``` -------------------------------- ### Memorable Password Recipe Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines the structure for generating memorable passwords. This recipe type uses words and separators to create human-readable passwords. ```python class PasswordRecipeMemorable(BaseModel): type: Literal["Memorable"] parameters: PasswordRecipeMemorableInner ``` -------------------------------- ### Create a Single Item Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items.md Use this method to create a new item in a specified vault. It requires an ItemCreateParams object detailing the item's properties. ```Python from onepassword import Client, ItemCreateParams, ItemField, ItemFieldType, ItemCategory, ItemSection async def main(): client = await Client.authenticate(...) item = await client.items.create( ItemCreateParams( title="My Login", category=ItemCategory.LOGIN, vault_id="vault_id", fields=[ ItemField( id="username", title="username", field_type=ItemFieldType.TEXT, value="myusername" ), ItemField( id="password", title="password", field_type=ItemFieldType.CONCEALED, value="mypassword" ) ], sections=[ItemSection(id="", title="")] ) ) print(f"Created item {item.id} in vault {item.vault_id}") ``` -------------------------------- ### Handling Concurrent Item Updates with Retries Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/errors.md Implement a retry mechanism to handle `itemStatusIncorrectItemVersion` errors by fetching the latest item version and reapplying updates. ```python async def update_with_retry(client, vault_id, item_id, update_fn): for attempt in range(3): try: # Get latest version item = await client.items.get(vault_id, item_id) # Apply updates update_fn(item) # Update item return await client.items.put(item) except Exception as e: if "itemStatusIncorrectItemVersion" in str(e) and attempt < 2: continue raise ``` -------------------------------- ### Generate a Random Password Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/secrets.md Use this snippet to generate a random password with specified criteria such as length, inclusion of digits, and symbols. Ensure the necessary classes are imported. ```python from onepassword import Secrets, PasswordRecipeRandom, PasswordRecipeRandomInner random_password = Secrets.generate_password( PasswordRecipeRandom( parameters=PasswordRecipeRandomInner( length=16, includeDigits=True, includeSymbols=True ) ) ) print(f"Generated password: {random_password.password}") ``` -------------------------------- ### Generate a Memorable Password Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/secrets.md This snippet generates a memorable password using a word list, separator, and capitalization options. It requires importing specific classes for memorable password generation. ```python from onepassword import ( Secrets, PasswordRecipeMemorable, PasswordRecipeMemorableInner, SeparatorType, WordListType ) memorable = Secrets.generate_password( PasswordRecipeMemorable( parameters=PasswordRecipeMemorableInner( separatorType=SeparatorType.HYPHENS, wordListType=WordListType.FULLWORDS, capitalize=True, wordCount=4 ) ) ) print(f"Generated password: {memorable.password}") ``` -------------------------------- ### Attach File to Item Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/api-reference/items-files.md Attaches a file to an existing item. Ensure the item and file parameters are correctly formatted. This operation may fail due to size limits or validation errors. ```python from onepassword import FileCreateParams async def main(): client = await Client.authenticate(...) # Get the item item = await client.items.get(vault_id, item_id) # Read file content file_content = b"file content here" # Attach file updated_item = await client.items.files.attach( item, FileCreateParams( name="document.pdf", content=file_content, sectionId="", fieldId="my_file_field" ) ) print(f"Attached file to item {updated_item.id}") ``` -------------------------------- ### PasswordRecipeMemorable Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Parameters for generating a memorable password. ```APIDOC ## PasswordRecipeMemorable Parameters for memorable password generation. ```python class PasswordRecipeMemorable(BaseModel): type: Literal["Memorable"] parameters: PasswordRecipeMemorableInner ``` ``` -------------------------------- ### Item Share Account Policy Model Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/types.md Defines account-wide policies for sharing items. This includes setting maximum and default expiration times, view limits, and allowed sharing configurations. ```python class ItemShareAccountPolicy(BaseModel): max_expiry: ItemShareDuration # alias: maxExpiry default_expiry: ItemShareDuration # alias: defaultExpiry max_views: Optional[int] # alias: maxViews allowed_types: List[AllowedType] # alias: allowedTypes allowed_recipient_types: List[AllowedRecipientType] # alias: allowedRecipientTypes files: ItemShareFiles ``` -------------------------------- ### ItemsFiles Source: https://github.com/1password/onepassword-sdk-python/blob/main/_autodocs/INDEX.md Manages file attachments to items, including attaching, reading, deleting, and replacing files. ```APIDOC ## ItemsFiles API ### Description Manages file operations for 1Password items, including attaching, reading, deleting, and replacing files. ### Methods - `attach(item_id: str, file_data: dict)`: Attach a file to an item. - `read(item_id: str, file_id: str)`: Read the content of a file attached to an item. - `delete(item_id: str, file_id: str)`: Delete a file from an item. - `replace_document(item_id: str, file_id: str, file_data: dict)`: Replace a document item's file. ```