1Password Connect SDK for Python

repository·main·Indexed 42 days ago

https://github.com/1password/connect-sdk-python

A Python SDK (version 2.1.0) that provides a programmatic way for applications to interact with 1Password items hosted on a self-hosted 1Password Connect server. It supports synchronous and asynchronous clients for managing items and vaults, including creating, retrieving, updating, and deleting secrets.

Tokens
9.9K
Snippets
34
Records
39
Agent score
53%

What's inside 1Password Connect SDK

  1. Configure 1Password Connect environment variables

    main

    The SDK requires specific environment variables to connect to your 1Password Connect server.

    Required variables:

    • OP_CONNECT_HOST: The URL of your self-hosted 1Password Connect server.
    • OP_CONNECT_TOKEN: The access token for your Connect server.

    Optional variables:

    • OP_CONNECT_CLIENT_REQ_TIMEOUT: Sets the timeout for client requests (e.g., 90 for 90 seconds).
    export OP_CONNECT_HOST=<your-connect-host> && \
    export OP_CONNECT_TOKEN=<your-connect-token>
    
    # Optional: set the timeout to 90 seconds
    export OP_CONNECT_CLIENT_REQ_TIMEOUT=90
  2. Configure the Client with ClientConfig

    main

    The ClientConfig class allows you to customize the underlying httpx client. This is useful for SSL settings, timeouts, proxies, and custom headers. All httpx client options are accepted as keyword arguments in ClientConfig.

    Common use cases:

    • SSL Verification: Use ca_file to specify a custom CA certificate or verify=False to disable verification (not recommended for production).
    • Timeouts & Redirects: Set timeout, follow_redirects, and max_redirects.
    • Proxies: Pass a dictionary to proxies mapping protocols to proxy URLs.
    • Headers: Pass a dictionary to headers for custom HTTP headers.
    from onepasswordconnectsdk.config import ClientConfig
    from onepasswordconnectsdk.client import new_client
    
    # Example: Custom CA and timeouts
    config = ClientConfig(
        ca_file="path/to/ca.pem",
        timeout=30.0,
        follow_redirects=True,
        max_redirects=5
    )
    client = new_client("https://connect.example.com", "your-token", config=config)
    
    # Example: Proxy settings
    proxy_config = ClientConfig(
        proxies={
            "http://": "http://proxy.example.com",
            "https://": "https://proxy.example.com"
        }
    )
    client = new_client("https://connect.example.com", "your-token", config=proxy_config)
  3. Use the Async Client

    main

    For asynchronous applications, initialize the client with is_async=True. All client methods must be awaited. It is recommended to close the client session gracefully using await client.session.aclose() when finished.

    import asyncio
    from onepasswordconnectsdk.client import new_client
    
    async_client = new_client(
        "{1Password_Connect_Host}",
        "{1Password_Connect_API_Token}",
        is_async=True
    )
    
    async def main():
        vaults = await async_client.get_vaults()
        item = await async_client.get_item("{item_id}", "{vault_id}")
        # ... do work ...
        await async_client.session.aclose()
    
    asyncio.run(main())
  4. Build and run the Python Connect SDK example via Docker

    main

    The example demonstrates item manipulation: creating an item from a secret string, adding it to a vault, retrieving it, and deleting it.

    To run the example, first build the Docker image:

    docker build -t python-connect-sdk-example .

    Then, run the container by passing your connection details as environment variables. If your Connect instance is running locally on your host machine, set OP_CONNECT_HOST to http://host.docker.internal:8080.

    docker run -it -e OP_CONNECT_TOKEN=<YOUR_CONNECT_TOKEN> -e OP_VAULT=<YOUR_VAULT_ID> \
        -e OP_CONNECT_HOST=<YOUR_CONNECT_HOST> -e SECRET_STRING=<ANY_RANDOM_STRING> \
        python-connect-sdk-example
  5. Prerequisites for using the Python Connect SDK

    main

    To use the Python Connect SDK and run the provided examples, you must have the following components configured:

    1. Docker: Installed and running on your machine.
    2. 1Password Connect Instance: A running instance of 1Password Connect hosted on your infrastructure.
    3. Connect Token: A valid token with read/write permissions for at least one vault accessible by the service account.
  6. Create a Connect API Client

    main

    You can instantiate a Client using two primary methods:

    1. From Environment Variables: Use new_client_from_environment() to automatically pick up OP_CONNECT_TOKEN and OP_CONNECT_HOST from your environment.
    2. Explicitly: Use new_client(hostname, token) to provide the 1Password Connect host and API token directly.

    To create an asynchronous client, pass True as the third positional argument to new_client (or use the is_async=True keyword argument).

    from onepasswordconnectsdk.client import (
        Client,
        new_client_from_environment,
        new_client
    )
    
    # Using environment variables
    connect_client_from_env: Client = new_client_from_environment()
    
    # Using explicit hostname and token
    connect_client_from_token: Client = new_client(
        "{1Password_Connect_Host}",
        "{1Password_Connect_API_Token}")
    
    # Creating an async client
    connect_async_client: Client = new_client(
        "{1Password_Connect_Host}",
        "{1Password_Connect_API_Token}",
        True)
  7. Load Configuration from 1Password

    main

    The SDK provides two convenience methods to map 1Password item fields directly into Python data structures (dictionaries or class objects).

    Using load_dict

    Pass a dictionary where keys are your desired output names, and values are sub-dictionaries defining the opitem, opfield, and opvault.

    Using load

    Pass a class where attributes are annotated with string tags (e.g., 'opitem:"Name" opvault:id opfield:path'). The method will populate the object attributes with the retrieved values.

    This is highly useful for loading application secrets (like database passwords) into a configuration object at startup.

    # Method 1: load_dict
    CONFIG = {
        "password": {
            "opitem": "My database item",
            "opfield": ".password",
            "opvault": "some_vault_id",
        },
    }
    values_dict = onepasswordconnectsdk.load_dict(connect_client, CONFIG)
    
    # Method 2: load (Class-based)
    class Config:
        password: 'opitem:"My database item" opvault:some_vault_id opfield:.password' = None
    
    CONFIG_OBJ = Config()
    values_object = onepasswordconnectsdk.load(connect_client, CONFIG_OBJ)
  8. How the Client handles errors

    main

    The SDK uses specific exception classes to help you identify what went wrong during API interactions:

    • FailedToRetrieveItemException: Raised when an item cannot be found, or when an error occurs during item-related operations (GET, POST, PUT, DELETE).
    • FailedToRetrieveVaultException: Raised when a vault cannot be found or when vault-related operations fail.
    • EnvironmentHostNotSetException: Raised when new_client_from_environment() is called but OP_CONNECT_HOST is missing.
    • EnvironmentTokenNotSetException: Raised when new_client_from_environment() is called but OP_CONNECT_TOKEN is missing.

    For FailedToRetrieveItemException, you can often inspect the status_code attribute to differentiate between a 404 (Not Found) and other HTTP errors.

  9. Initialize Async vs Sync clients

    main

    The SDK provides both synchronous and asynchronous clients. You can choose between them using the new_client factory function by setting the is_async parameter.

    • is_async=False (default): Returns a standard Client using httpx.Client.
    • is_async=True: Returns an AsyncClient using httpx.AsyncClient.

    This choice is also driven by the OP_CONNECT_CLIENT_ASYNC environment variable when using new_client_from_environment().

    from onepasswordconnectsdk import new_client
    
    # Synchronous client
    sync_client = new_client(url, token, is_async=False)
    
    # Asynchronous client
    async_client = new_client(url, token, is_async=True)
  10. Create a client from environment variables

    main

    You can use new_client_from_environment() to automatically configure the client using environment variables. This is useful for containerized or CI/CD environments.

    Required environment variables:

    • OP_CONNECT_HOST: The URL of the 1Password Connect API.
    • OP_CONNECT_TOKEN: The 1Password Service Account token.

    Optional environment variables:

    • OP_CONNECT_CLIENT_ASYNC: Set to True to initialize an AsyncClient instead of a synchronous Client.
    from onepasswordconnectsdk import new_client_from_environment
    
    # Automatically uses OP_CONNECT_HOST and OP_CONNECT_TOKEN
    client = new_client_from_environment()
  11. Initialize the 1Password Connect Client

    main

    To interact with the 1Password Connect API, use the Client class or the new_client factory function. You must provide the API url and a 1Password Service Account token. You can optionally provide a ClientConfig to customize the underlying httpx client behavior.

    from onepasswordconnectsdk import Client
    
    client = Client(
        url="https://your-connect-host.com",
        token="your-service-account-token"
    )