### Get User Guide Channel Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a specific user's guide channel. Optional parameters can be passed for customization. ```python from knockapi.types.users import GuideGetChannelResponse # Assuming 'client' is an initialized Knock client instance # user_id = "some_user_id" # channel_id = "some_channel_id" # params = {} # response: GuideGetChannelResponse = client.users.guides.get_channel(user_id, channel_id, **params) ``` -------------------------------- ### Install Knock Python SDK Source: https://context7.com/knocklabs/knock-python/llms.txt Install the Knock Python SDK using pip. For asynchronous support with aiohttp, install with the `aiohttp` extra. ```bash pip install knockapi # For async support with aiohttp pip install knockapi[aiohttp] ``` -------------------------------- ### Get User Guide Channel Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a specific user's guide channel with optional parameters. ```APIDOC ## GET /v1/users/{user_id}/guides/{channel_id} ### Description Retrieves a specific user's guide channel with optional parameters. ### Method GET ### Endpoint /v1/users/{user_id}/guides/{channel_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **channel_id** (string) - Required - The ID of the guide channel. #### Query Parameters - **page_size** (integer) - Optional - The number of items to retrieve per page. - **current** (string) - Optional - The current item ID for pagination. ### Response #### Success Response (200) - **channel** (object) - The guide channel details. ``` -------------------------------- ### Install Knock Python API Source: https://github.com/knocklabs/knock-python/blob/main/README.md Install the Knock Python API library using pip. ```sh pip install knockapi ``` -------------------------------- ### Add and Run Python Example Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Add new examples to the `examples/` directory. Make the script executable and then run it against your API. The `#!/usr/bin/env -S rye run python` shebang ensures it runs with the correct Python interpreter managed by Rye. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh $ chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Build and Install knock-python Wheel Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Build a distributable wheel file for the library using Rye or Python's build module. Then, install the library using the generated wheel file. ```sh $ rye build # or $ python -m build ``` ```sh $ pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install Knock API with aiohttp support Source: https://github.com/knocklabs/knock-python/blob/main/README.md Install the Knock Python API library with aiohttp support for improved concurrency. ```sh pip install knockapi[aiohttp] ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip. Ensure the Python version specified in .python-version is used and a virtual environment is created. ```sh $ pip install -r requirements-dev.lock ``` -------------------------------- ### Install knock-python from Git Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Install the knock-python library directly from its Git repository using pip. This is useful for using the latest development version. ```sh $ pip install git+ssh://git@github.com/knocklabs/knock-python.git ``` -------------------------------- ### Mark User Guide Message as Seen Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message within a user's guide as seen. Optional parameters can be provided. ```python from knockapi.types.users import GuideMarkMessageAsSeenResponse # Assuming 'client' is an initialized Knock client instance # user_id = "some_user_id" # message_id = "some_message_id" # params = {} # response: GuideMarkMessageAsSeenResponse = client.users.guides.mark_message_as_seen(user_id, message_id, **params) ``` -------------------------------- ### Asynchronous Client with aiohttp Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of instantiating the asynchronous Knock client with `aiohttp` as the HTTP backend. ```APIDOC ## Asynchronous Client with aiohttp ### Description Instantiate the asynchronous Knock client using `aiohttp` for improved concurrency. ### Method `await client.workflows.trigger()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of the workflow to trigger. - **recipients** (list of strings) - Required - A list of recipient identifiers. - **data** (dict) - Optional - Additional data to pass to the workflow. ### Request Example ```python import os import asyncio from knockapi import DefaultAioHttpClient from knockapi import AsyncKnock async def main() -> None: async with AsyncKnock( api_key=os.environ.get("KNOCK_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: response = await client.workflows.trigger( key="dinosaurs-loose", recipients=["dnedry"], data={"dinosaur": "triceratops"}, ) print(response.workflow_run_id) asyncio.run(main()) ``` ### Response #### Success Response (200) - **workflow_run_id** (string) - The ID of the triggered workflow run. #### Response Example ```json { "workflow_run_id": "some-run-id" } ``` ``` -------------------------------- ### Get Installed Knock SDK Version Source: https://github.com/knocklabs/knock-python/blob/main/README.md Determine the version of the Knock SDK being used at runtime by accessing the `__version__` attribute. ```python import knockapi print(knockapi.__version__) ``` -------------------------------- ### Start Mock Server for Tests Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Run this script to set up a mock server. This server is required to run most of the project's tests against the OpenAPI specification. ```sh $ ./scripts/mock ``` -------------------------------- ### Mark User Guide Message as Seen Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message in a user's guide as seen. ```APIDOC ## PUT /v1/users/{user_id}/guides/messages/{message_id}/seen ### Description Marks a specific message in a user's guide as seen. ### Method PUT ### Endpoint /v1/users/{user_id}/guides/messages/{message_id}/seen ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **message_id** (string) - Required - The ID of the message. ### Response #### Success Response (200) - **message** (object) - The updated message details. ``` -------------------------------- ### Asynchronous Client Usage Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of how to instantiate and use the asynchronous Knock client to trigger a workflow. ```APIDOC ## Asynchronous Client Usage ### Description Instantiate the asynchronous Knock client and trigger a workflow using `await`. ### Method `await client.workflows.trigger()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of the workflow to trigger. - **recipients** (list of strings) - Required - A list of recipient identifiers. - **data** (dict) - Optional - Additional data to pass to the workflow. ### Request Example ```python import os import asyncio from knockapi import AsyncKnock client = AsyncKnock( api_key=os.environ.get("KNOCK_API_KEY"), # This is the default and can be omitted ) async def main() -> None: response = await client.workflows.trigger( key="dinosaurs-loose", recipients=["dnedry"], data={"dinosaur": "triceratops"}, ) print(response.workflow_run_id) asyncio.run(main()) ``` ### Response #### Success Response (200) - **workflow_run_id** (string) - The ID of the triggered workflow run. #### Response Example ```json { "workflow_run_id": "some-run-id" } ``` ``` -------------------------------- ### Synchronous Client Usage Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of how to instantiate and use the synchronous Knock client to trigger a workflow. ```APIDOC ## Synchronous Client Usage ### Description Instantiate the synchronous Knock client and trigger a workflow. ### Method `client.workflows.trigger()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of the workflow to trigger. - **recipients** (list of strings) - Required - A list of recipient identifiers. - **data** (dict) - Optional - Additional data to pass to the workflow. ### Request Example ```python import os from knockapi import Knock client = Knock( api_key=os.environ.get("KNOCK_API_KEY"), # This is the default and can be omitted ) response = client.workflows.trigger( key="dinosaurs-loose", recipients=["dnedry"], data={"dinosaur": "triceratops"}, ) print(response.workflow_run_id) ``` ### Response #### Success Response (200) - **workflow_run_id** (string) - The ID of the triggered workflow run. #### Response Example ```json { "workflow_run_id": "some-run-id" } ``` ``` -------------------------------- ### Mark User Guide Message as Archived Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message within a user's guide as archived. Optional parameters can be provided. ```python from knockapi.types.users import GuideMarkMessageAsArchivedResponse # Assuming 'client' is an initialized Knock client instance # user_id = "some_user_id" # message_id = "some_message_id" # params = {} # response: GuideMarkMessageAsArchivedResponse = client.users.guides.mark_message_as_archived(user_id, message_id, **params) ``` -------------------------------- ### Client Initialization Source: https://context7.com/knocklabs/knock-python/llms.txt Initialize the Knock client with your API key to start making API calls. The client can be configured with custom timeouts, retries, and HTTP settings. ```APIDOC ## Client Initialization Initialize the Knock client with your API key to start making API calls. The client can be configured with custom timeouts, retries, and HTTP settings. ```python import os from knockapi import Knock, AsyncKnock # Synchronous client - API key from environment variable client = Knock( api_key=os.environ.get("KNOCK_API_KEY"), # defaults to KNOCK_API_KEY env var ) # Or with explicit configuration client = Knock( api_key="sk_test_your_api_key", timeout=20.0, # 20 seconds (default is 60) max_retries=3, # default is 2 ) # Async client async_client = AsyncKnock( api_key=os.environ.get("KNOCK_API_KEY"), ) ``` ``` -------------------------------- ### List User Messages with Nested Parameters Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of how to list user messages, demonstrating the use of nested parameters like `inserted_at`. ```APIDOC ## Nested params Nested parameters are dictionaries, typed using `TypedDict`, for example: ```python from knockapi import Knock client = Knock() page = client.users.list_messages( user_id="user-123", inserted_at={}, ) print(page.items) ``` ``` -------------------------------- ### Asynchronous Pagination Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of iterating through paginated list results using the asynchronous client. ```APIDOC ## Asynchronous Pagination ### Description Iterate through all items in a paginated list using the asynchronous client's auto-paginating iterator. ### Method `async for user in client.users.list():` ### Parameters None ### Request Example ```python import asyncio from knockapi import AsyncKnock client = AsyncKnock() async def main() -> None: all_users = [] # Iterate through items across all pages, issuing requests as needed. async for user in client.users.list(): all_users.append(user) print(all_users) asyncio.run(main()) ``` ### Response #### Success Response (200) - **entries** (list) - A list of items on the current page. - **page_info** (object) - Information about the current page and next page. #### Response Example ```json { "entries": [ { "id": "user-1", "name": "John Doe" }, { "id": "user-2", "name": "Jane Smith" } ], "page_info": { "after": "cursor-for-next-page", "has_more": true } } ``` ``` -------------------------------- ### Synchronous Pagination Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of iterating through paginated list results using the synchronous client. ```APIDOC ## Synchronous Pagination ### Description Iterate through all items in a paginated list using the synchronous client's auto-paginating iterator. ### Method `client.users.list()` ### Parameters None ### Request Example ```python from knockapi import Knock client = Knock() all_users = [] # Automatically fetches more pages as needed. for user in client.users.list(): # Do something with user here all_users.append(user) print(all_users) ``` ### Response #### Success Response (200) - **entries** (list) - A list of items on the current page. - **page_info** (object) - Information about the current page and next page. #### Response Example ```json { "entries": [ { "id": "user-1", "name": "John Doe" }, { "id": "user-2", "name": "Jane Smith" } ], "page_info": { "after": "cursor-for-next-page", "has_more": true } } ``` ``` -------------------------------- ### Manual Pagination Control Source: https://github.com/knocklabs/knock-python/blob/main/README.md Example of manually controlling pagination using `.has_next_page()`, `.next_page_info()`, and `.get_next_page()`. ```APIDOC ## Manual Pagination Control ### Description Manually control pagination by checking for the next page, retrieving its information, and fetching it. ### Method `client.users.list()`, `.has_next_page()`, `.next_page_info()`, `.get_next_page()` ### Parameters None ### Request Example ```python # Assuming 'client' is an instance of Knock or AsyncKnock first_page = await client.users.list() # Use `await` for async client if first_page.has_next_page(): print(f"will fetch next page using these details: {first_page.next_page_info()}") next_page = await first_page.get_next_page() # Use `await` for async client print(f"number of items we just fetched: {len(next_page.entries)}") # Remove `await` for non-async usage. ``` ### Response #### Success Response (200) - **entries** (list) - A list of items on the fetched page. - **page_info** (object) - Information about the current page and next page. #### Response Example ```json { "entries": [ { "id": "user-3", "name": "Peter Jones" } ], "page_info": { "after": "cursor-for-next-page", "has_more": false } } ``` ``` -------------------------------- ### Mark User Guide Message as Interacted Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message within a user's guide as interacted. Optional parameters can be provided. ```python from knockapi.types.users import GuideMarkMessageAsInteractedResponse # Assuming 'client' is an initialized Knock client instance # user_id = "some_user_id" # message_id = "some_message_id" # params = {} # response: GuideMarkMessageAsInteractedResponse = client.users.guides.mark_message_as_interacted(user_id, message_id, **params) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md If installing Rye manually, use this command to sync all dependencies, including development features. Ensure Python version is set in .python-version. ```sh $ rye sync --all-features ``` -------------------------------- ### Get a Tenant Source: https://context7.com/knocklabs/knock-python/llms.txt Retrieve details for a specific tenant using its ID. This is useful for verifying tenant configuration or fetching dynamic settings. ```python tenant = client.tenants.get("acme-corp") ``` -------------------------------- ### Get All User Preferences Source: https://context7.com/knocklabs/knock-python/llms.txt Retrieves all preference sets for a given user. Iterates through the results to print each preference set ID. ```python preferences = client.users.list_preferences("user_123") for pref_set in preferences: print(f"Preference set: {pref_set.id}") ``` -------------------------------- ### Get User Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a specific user by their ID. ```python client.users.get(user_id) ``` -------------------------------- ### Mark User Guide Message as Archived Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message in a user's guide as archived. ```APIDOC ## PUT /v1/users/{user_id}/guides/messages/{message_id}/archived ### Description Marks a specific message in a user's guide as archived. ### Method PUT ### Endpoint /v1/users/{user_id}/guides/messages/{message_id}/archived ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **message_id** (string) - Required - The ID of the message. ### Response #### Success Response (200) - **message** (object) - The updated message details. ``` -------------------------------- ### Get User Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a single user by their ID. ```APIDOC ## GET /v1/users/{user_id} ### Description Retrieves a user. ### Method GET ### Endpoint /v1/users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. ``` -------------------------------- ### Get Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a specific object by its collection and ID. ```APIDOC ## GET /v1/objects/{collection}/{id} ### Description Retrieves a specific object by its collection and ID. ### Method GET ### Endpoint /v1/objects/{collection}/{id} ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **id** (string) - Required - The ID of the object. ``` -------------------------------- ### Get User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the preferences for a specific user and preference set ID. Optional parameters can be provided. ```python client.users.get_preferences(user_id, id, **params) ``` -------------------------------- ### Get Specific User Preference Set Source: https://context7.com/knocklabs/knock-python/llms.txt Fetches a specific preference set for a user by providing both the user ID and the preference set ID. ```python prefs = client.users.get_preferences( user_id="user_123", id="default", # preference set ID ) ``` -------------------------------- ### Create or Update a Tenant Source: https://context7.com/knocklabs/knock-python/llms.txt Use this method to create a new tenant or update an existing one with specified settings. Ensure the client is initialized with appropriate credentials. ```python tenant = client.tenants.set( id="acme-corp", name="Acme Corporation", settings={ "branding": { "logo_url": "https://acme.com/logo.png", "primary_color": "#FF5733", }, "timezone": "America/Los_Angeles", }, ) print(f"Tenant: {tenant.id}") ``` -------------------------------- ### User Preferences Source: https://context7.com/knocklabs/knock-python/llms.txt Manage user notification preferences, including retrieving all preference sets, getting a specific set, and setting or merging preferences. ```APIDOC ## User Preferences ### Get all preference sets for a user ```python preferences = client.users.list_preferences("user_123") for pref_set in preferences: print(f"Preference set: {pref_set.id}") ``` ### Get a specific preference set ```python prefs = client.users.get_preferences( user_id="user_123", id="default", # preference set ID ) ``` ### Set user preferences (replaces existing by default) ```python prefs = client.users.set_preferences( user_id="user_123", id="default", channel_types={ "email": True, "sms": False, "push": True, "in_app_feed": True, }, workflows={ "marketing-emails": False, # Opt out of marketing "security-alerts": True, }, categories={ "transactional": {"email": True, "push": True}, "promotional": {"email": False, "push": False}, }, ) ``` ### Merge with existing preferences instead of replacing ```python prefs = client.users.set_preferences( user_id="user_123", id="default", _persistence_strategy="merge", workflows={ "weekly-digest": True, }, ) ``` ``` -------------------------------- ### Get User Feed Settings Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the settings for a specific user's feed. Ensure the user ID and feed ID are correctly provided. ```python from knockapi.types.users import FeedGetSettingsResponse # Assuming 'client' is an initialized Knock client instance # user_id = "some_user_id" # feed_id = "some_feed_id" # response: FeedGetSettingsResponse = client.users.feeds.get_settings(user_id, feed_id) ``` -------------------------------- ### Mark User Guide Message as Interacted Source: https://github.com/knocklabs/knock-python/blob/main/api.md Marks a specific message in a user's guide as interacted. ```APIDOC ## PUT /v1/users/{user_id}/guides/messages/{message_id}/interacted ### Description Marks a specific message in a user's guide as interacted. ### Method PUT ### Endpoint /v1/users/{user_id}/guides/messages/{message_id}/interacted ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **message_id** (string) - Required - The ID of the message. ### Response #### Success Response (200) - **message** (object) - The updated message details. ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Run this script to automatically set up the Python environment using Rye. It ensures the correct Python version and manages dependencies. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### Run Project Tests Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Execute the project's test suite. Ensure the mock server is running if required by the tests. ```sh $ ./scripts/test ``` -------------------------------- ### Configure Granular Timeout Settings Source: https://github.com/knocklabs/knock-python/blob/main/README.md Illustrates how to configure more granular timeout settings (read, write, connect) using an `httpx.Timeout` object. ```python import httpx from knockapi import Knock client = Knock( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) ``` -------------------------------- ### Enabling Logging Source: https://github.com/knocklabs/knock-python/blob/main/README.md Instructions on how to enable logging for the SDK by setting the `KNOCK_LOG` environment variable to 'info' or 'debug'. ```APIDOC ### Logging We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. You can enable logging by setting the environment variable `KNOCK_LOG` to `info`. ```shell $ export KNOCK_LOG=info ``` Or to `debug` for more verbose logging. ``` -------------------------------- ### Get Message Content Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the content of a specific message. ```APIDOC ## GET /v1/messages/{message_id}/content ### Description Retrieves the content of a specific message. ### Method GET ### Endpoint /v1/messages/{message_id}/content ### Parameters #### Path Parameters - **message_id** (string) - Required - The unique identifier of the message whose content to retrieve. ### Response #### Success Response (200) - **MessageGetContentResponse** - An object containing the content of the message. ``` -------------------------------- ### Initialize Knock Client (Python) Source: https://context7.com/knocklabs/knock-python/llms.txt Initialize the Knock client with your API key. The API key can be read from an environment variable or provided explicitly. Custom timeouts and retry counts can also be configured. ```python import os from knockapi import Knock, AsyncKnock # Synchronous client - API key from environment variable client = Knock( api_key=os.environ.get("KNOCK_API_KEY"), # defaults to KNOCK_API_KEY env var ) # Or with explicit configuration client = Knock( api_key="sk_test_your_api_key", timeout=20.0, # 20 seconds (default is 60) max_retries=3, # default is 2 ) # Async client async_client = AsyncKnock( api_key=os.environ.get("KNOCK_API_KEY"), ) ``` -------------------------------- ### Get Message Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a single message by its unique identifier. ```APIDOC ## GET /v1/messages/{message_id} ### Description Retrieves a single message by its unique identifier. ### Method GET ### Endpoint /v1/messages/{message_id} ### Parameters #### Path Parameters - **message_id** (string) - Required - The unique identifier of the message to retrieve. ### Response #### Success Response (200) - **Message** - The requested Message object. ``` -------------------------------- ### Get Object Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the preference set for a specific object. ```APIDOC ## GET /v1/objects/{collection}/{object_id}/preferences/{id} ### Description Retrieves the preference set for a specific object. ### Method GET ### Endpoint /v1/objects/{collection}/{object_id}/preferences/{id} ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **object_id** (string) - Required - The ID of the object. - **id** (string) - Required - The ID of the preference set. ``` -------------------------------- ### Bulk Set User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Initiates a bulk operation to set user preferences. Requires parameters specifying users and their preference changes. ```python from knockapi.types.bulk_operation import BulkOperation # Assuming 'client' is an initialized Knock client instance # params = {} # response: BulkOperation = client.users.bulk.set_preferences(**params) ``` -------------------------------- ### Get Object Channel Data Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves channel-specific data for a given object. ```APIDOC ## GET /v1/objects/{collection}/{object_id}/channel_data/{channel_id} ### Description Retrieves channel-specific data for a given object. ### Method GET ### Endpoint /v1/objects/{collection}/{object_id}/channel_data/{channel_id} ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **object_id** (string) - Required - The ID of the object. - **channel_id** (string) - Required - The ID of the channel. ``` -------------------------------- ### Get a Specific Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieve the details of a single object by its collection and ID. ```python client.objects.get(collection, id) ``` -------------------------------- ### Manual Pagination Control Source: https://github.com/knocklabs/knock-python/blob/main/README.md Demonstrates granular control over pagination using `.has_next_page()`, `.next_page_info()`, and `.get_next_page()` methods. Remove `await` for non-async usage. ```python first_page = await client.users.list() if first_page.has_next_page(): print(f"will fetch next page using these details: {first_page.next_page_info()}") next_page = await first_page.get_next_page() print(f"number of items we just fetched: {len(next_page.entries)}") # Remove `await` for non-async usage. ``` -------------------------------- ### Enable Knock SDK Logging Source: https://github.com/knocklabs/knock-python/blob/main/README.md Explains how to enable logging for the Knock SDK by setting the `KNOCK_LOG` environment variable to `info` or `debug`. ```shell $ export KNOCK_LOG=info ``` -------------------------------- ### Get User Feed Settings Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the settings for a specific user's feed. ```APIDOC ## GET /v1/users/{user_id}/feeds/{id}/settings ### Description Retrieves the settings for a specific user's feed. ### Method GET ### Endpoint /v1/users/{user_id}/feeds/{id}/settings ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user. - **id** (string) - Required - The ID of the feed. ### Response #### Success Response (200) - **settings** (object) - The feed settings. ``` -------------------------------- ### Set User Preferences (Merge) Source: https://context7.com/knocklabs/knock-python/llms.txt Merges new preferences with existing ones instead of replacing them entirely. Use the `_persistence_strategy='merge'` argument. ```python prefs = client.users.set_preferences( user_id="user_123", id="default", _persistence_strategy="merge", workflows={ "weekly-digest": True, }, ) ``` -------------------------------- ### Get User Channel Data Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the channel data for a specific user and channel. ```APIDOC ## GET /v1/users/{user_id}/channel_data/{channel_id} ### Description Retrieves the channel data for a specific user and channel. ### Method GET ### Endpoint /v1/users/{user_id}/channel_data/{channel_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. - **channel_id** (string) - Required - The unique identifier for the channel. ``` -------------------------------- ### Paginate Users (Asynchronous) Source: https://github.com/knocklabs/knock-python/blob/main/README.md Use the asynchronous client to iterate through all users, automatically fetching subsequent pages. Requires `async for`. ```python import asyncio from knockapi import AsyncKnock client = AsyncKnock() async def main() -> None: all_users = [] # Iterate through items across all pages, issuing requests as needed. async for user in client.users.list(): all_users.append(user) print(all_users) asyncio.run(main()) ``` -------------------------------- ### Get an Object Source: https://context7.com/knocklabs/knock-python/llms.txt Retrieves a specific object from a collection using its collection name and ID. ```python from knockapi import Knock client = Knock() # Get an object obj = client.objects.get( collection="projects", id="project_001", ) ``` -------------------------------- ### Manage Users (Python) Source: https://context7.com/knocklabs/knock-python/llms.txt Create, update, retrieve, list, delete, and merge users in Knock. Users are identified by a unique ID and can have associated properties like name, email, and phone number. ```python from knockapi import Knock client = Knock() # Create or update a user (identify) user = client.users.update( user_id="user_123", name="John Doe", email="john@example.com", phone_number="+15551234567", avatar="https://example.com/avatars/john.png", timezone="America/New_York", locale="en-US", ) print(f"User: {user.id}, Email: {user.email}") # Get a specific user user = client.users.get("user_123") print(f"User name: {user.name}") # List all users with pagination for user in client.users.list(page_size=50): print(f"User: {user.id} - {user.name}") # Manual pagination control first_page = client.users.list(page_size=10) for user in first_page.entries: print(user.id) if first_page.has_next_page(): next_page = first_page.get_next_page() # Delete a user client.users.delete("user_123") # Merge two users merged_user = client.users.merge( user_id="primary_user", from_user_id="duplicate_user", ) ``` -------------------------------- ### Paginate Users (Synchronous) Source: https://github.com/knocklabs/knock-python/blob/main/README.md Use the synchronous client to iterate through all users, automatically fetching subsequent pages. ```python from knockapi import Knock client = Knock() all_users = [] # Automatically fetches more pages as needed. for user in client.users.list(): # Do something with user here all_users.append(user) print(all_users) ``` -------------------------------- ### Publish PyPI Package Manually Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Manually release a package to PyPI by running the `bin/publish-pypi` script. Ensure the `PYPI_TOKEN` environment variable is set. ```sh bin/publish-pypi ``` -------------------------------- ### Get User Channel Data Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the channel-specific data for a given user and channel ID. ```python client.users.get_channel_data(user_id, channel_id) ``` -------------------------------- ### Bulk Set User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Initiates a bulk operation to set user preferences. ```APIDOC ## POST /v1/users/bulk/preferences ### Description Initiates a bulk operation to set user preferences. ### Method POST ### Endpoint /v1/users/bulk/preferences ### Parameters #### Request Body - **user_preferences** (array) - Required - A list of user preference objects. ### Response #### Success Response (200) - **operation_id** (string) - The ID of the bulk operation. ``` -------------------------------- ### Configure Knock Client with Custom HTTP Client Source: https://github.com/knocklabs/knock-python/blob/main/README.md Override the default httpx client to customize proxies, transports, or other advanced features. The `base_url` can also be set directly or via an environment variable. ```python import httpx from knockapi import Knock, DefaultHttpxClient client = Knock( # Or use the `KNOCK_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Get Channel Data for an Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Fetch the channel-specific data associated with an object for a given channel ID. ```python client.objects.get_channel_data(collection, object_id, channel_id) ``` -------------------------------- ### Get User Channel Data Source: https://context7.com/knocklabs/knock-python/llms.txt Retrieves channel-specific data for a user, such as push tokens or Slack connection details. ```python from knockapi import Knock client = Knock() # Get channel data channel_data = client.users.get_channel_data( user_id="user_123", channel_id="firebase-push", ) print(f"Channel: {channel_data.channel_id}") ``` -------------------------------- ### Get User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves the preferences for a specific user and preference set ID. Accepts optional parameters for filtering. ```APIDOC ## GET /v1/users/{user_id}/preferences/{id} ### Description Retrieves the preferences for a specific user and preference set ID. ### Method GET ### Endpoint /v1/users/{user_id}/preferences/{id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. - **id** (string) - Required - The unique identifier for the preference set. #### Query Parameters - **params** (object) - Optional - A dictionary containing parameters for filtering. ``` -------------------------------- ### List User Messages with Nested Params Source: https://github.com/knocklabs/knock-python/blob/main/README.md Demonstrates how to list user messages using nested parameters, specifically for the `inserted_at` field. Ensure the Knock client is initialized. ```python from knockapi import Knock client = Knock() page = client.users.list_messages( user_id="user-123", inserted_at={}, ) print(page.items) ``` -------------------------------- ### Create a Recurring Schedule Source: https://context7.com/knocklabs/knock-python/llms.txt Set up a workflow to run repeatedly based on a defined pattern (e.g., weekly on Mondays at 9 AM). Supports setting an end date for the recurrence. ```python schedules = client.schedules.create( workflow="weekly-report", recipients=["user_123", "user_456"], scheduled_at=datetime.now(), repeats=[ { "frequency": "weekly", "days": ["monday"], "hours": 9, "minutes": 0, } ], ending_at=datetime.now() + timedelta(days=365), data={"report_type": "weekly"}, ) ``` -------------------------------- ### Get Preferences for an Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieve the preference set for a specific object, identified by its collection, object ID, and preference set ID. ```python client.objects.get_preferences(collection, object_id, id) ``` -------------------------------- ### Set User Preferences (Replace) Source: https://context7.com/knocklabs/knock-python/llms.txt Sets user preferences, replacing existing ones by default. Allows configuration of channel types, workflows, and categories. ```python prefs = client.users.set_preferences( user_id="user_123", id="default", channel_types={ "email": True, "sms": False, "push": True, "in_app_feed": True, }, workflows={ "marketing-emails": False, # Opt out of marketing "security-alerts": True, }, categories={ "transactional": {"email": True, "push": True}, "promotional": {"email": False, "push": False}, }, ) ``` -------------------------------- ### Get Raw Response with Headers Source: https://context7.com/knocklabs/knock-python/llms.txt Access the raw HTTP response, including status code and headers, before parsing it into a typed object. ```python response = client.users.with_raw_response.get("user_123") print(f"Status: {response.status_code}") print(f"Headers: {response.headers}") user = response.parse() # Parse to typed object ``` -------------------------------- ### Get Message Content Source: https://context7.com/knocklabs/knock-python/llms.txt Retrieve the rendered content of a message, including subject and body, as it was presented to the recipient. Useful for debugging or auditing. ```python content = client.messages.get_content("msg_abc123") print(f"Subject: {content.data.get('subject')}") print(f"Body: {content.data.get('body')}") ``` -------------------------------- ### List Preferences for an Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieve all preference sets associated with a given object. ```python client.objects.list_preferences(collection, object_id) ``` -------------------------------- ### Manage HTTP Resources with Knock Client Context Manager Source: https://github.com/knocklabs/knock-python/blob/main/README.md Manually close the client using `.close()` or use a context manager (`with Knock() as client:`) to ensure HTTP connections are reliably closed when exiting the block. ```python from knockapi import Knock with Knock() as client: # make requests here ... ``` -------------------------------- ### List All Tenants Source: https://context7.com/knocklabs/knock-python/llms.txt Iterate through all tenants associated with your Knock account. This can be used for auditing or managing multiple tenant configurations. ```python for tenant in client.tenants.list(): print(f"Tenant: {tenant.id} - {tenant.name}") ``` -------------------------------- ### List User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves all preference sets associated with a specific user. ```python client.users.list_preferences(user_id) ``` -------------------------------- ### Get a Specific Message Source: https://context7.com/knocklabs/knock-python/llms.txt Fetch details of a single message using its unique ID. This allows inspection of message status, channel, and recipient information. ```python message = client.messages.get("msg_abc123") print(f"Status: {message.status}") print(f"Channel: {message.channel_id}") print(f"Recipient: {message.recipient.id}") ``` -------------------------------- ### Configuring Timeouts Source: https://github.com/knocklabs/knock-python/blob/main/README.md Details how to set request timeouts, both globally and per-request, using float values or httpx.Timeout objects. ```APIDOC ### Timeouts By default requests time out after 1 minute. You can configure this with a `timeout` option, which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: ```python from knockapi import Knock # Configure the default for all requests: client = Knock( # 20 seconds (default is 1 minute) timeout=20.0, ) # More granular control: client = Knock( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # Override per-request: client.with_options(timeout=5.0).users.get( "dnedry", ) ``` On timeout, an `APITimeoutError` is thrown. Note that requests that time out are [retried twice by default](#retries). ``` -------------------------------- ### Bulk Set Objects Source: https://context7.com/knocklabs/knock-python/llms.txt Use this to set multiple objects in a collection at once. Check the operation status afterward. ```python operation = client.objects.bulk.set( collection="projects", objects=[ {"id": "proj_001", "name": "Project Alpha"}, {"id": "proj_002", "name": "Project Beta"}, ], ) # Check bulk operation status op_status = client.bulk_operations.get(operation.id) print(f"Status: {op_status.status}") print(f"Progress: {op_status.processed_rows}/{op_status.total_rows}") ``` -------------------------------- ### List User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves all preference sets for a specific user. ```APIDOC ## GET /v1/users/{user_id}/preferences ### Description Retrieves all preference sets for a specific user. ### Method GET ### Endpoint /v1/users/{user_id}/preferences ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. ``` -------------------------------- ### Import Subscription Type Source: https://github.com/knocklabs/knock-python/blob/main/api.md Import the Subscription type for managing user subscriptions. ```python from knockapi.types.recipients import Subscription ``` -------------------------------- ### Import User Types Source: https://github.com/knocklabs/knock-python/blob/main/api.md Import types for user management, including IdentifyUserRequest, User, and UserListPreferencesResponse. ```python from knockapi.types import ( IdentifyUserRequest, InlineIdentifyUserRequest, User, UserListPreferencesResponse, ) ``` -------------------------------- ### Configure Per-Request Max Retries Source: https://github.com/knocklabs/knock-python/blob/main/README.md Demonstrates how to override the default retry settings for a specific API call using the `with_options` method. ```python client.with_options(max_retries=5).users.get( "dnedry", ) ``` -------------------------------- ### Bulk Set User Preferences Source: https://context7.com/knocklabs/knock-python/llms.txt Update notification preferences for multiple users simultaneously. Specify the user IDs and the desired preference settings for channels. ```python operation = client.users.bulk.set_preferences( user_ids=["user_001", "user_002", "user_003"], preferences={ "channel_types": { "email": True, "push": True, }, }, ) ``` -------------------------------- ### Set User Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Sets or updates the preferences for a user for a given preference set ID. Requires user ID, preference set ID, and preference parameters. ```python client.users.set_preferences(user_id, id, **params) ``` -------------------------------- ### Import Preference Types Source: https://github.com/knocklabs/knock-python/blob/main/api.md Import types for managing user preferences, including InlinePreferenceSetRequest, PreferenceSet, and various channel-related settings. ```python from knockapi.types.recipients import ( InlinePreferenceSetRequest, PreferenceSet, PreferenceSetChannelSetting, PreferenceSetChannelTypeSetting, PreferenceSetChannelTypes, PreferenceSetRequest, ) ``` -------------------------------- ### Bulk Identify Users Source: https://context7.com/knocklabs/knock-python/llms.txt Create or update multiple user profiles in a single operation. Provide a list of user objects, each with an ID and relevant attributes like name and email. ```python from knockapi import Knock client = Knock() # Bulk identify users operation = client.users.bulk.identify( users=[ {"id": "user_001", "name": "Alice", "email": "alice@example.com"}, {"id": "user_002", "name": "Bob", "email": "bob@example.com"}, {"id": "user_003", "name": "Charlie", "email": "charlie@example.com"}, ], ) print(f"Bulk operation ID: {operation.id}") ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/knocklabs/knock-python/blob/main/CONTRIBUTING.md Activate the virtual environment created by Rye to run Python scripts without the `rye run` prefix. This is a standard Python virtual environment activation. ```sh # Activate the virtual environment - https://docs.python.org/3/library/venv.html#how-venvs-work $ source .venv/bin/activate ``` -------------------------------- ### Configure Default Max Retries for Knock Client Source: https://github.com/knocklabs/knock-python/blob/main/README.md Illustrates how to set the default number of retries for all requests made by the Knock client. Setting `max_retries` to 0 disables retries. ```python from knockapi import Knock # Configure the default for all requests: client = Knock( # default is 2 max_retries=0, ) ``` -------------------------------- ### Bulk Identify Users Source: https://github.com/knocklabs/knock-python/blob/main/api.md Initiates a bulk identify operation for users. Requires parameters specifying user data for identification. ```python from knockapi.types.bulk_operation import BulkOperation # Assuming 'client' is an initialized Knock client instance # params = {} # response: BulkOperation = client.users.bulk.identify(**params) ``` -------------------------------- ### List Schedules for Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a paginated list of schedules associated with a specific object. ```APIDOC ## GET /v1/objects/{collection}/{id}/schedules ### Description Retrieves a paginated list of schedules associated with a specific object. ### Method GET ### Endpoint /v1/objects/{collection}/{id}/schedules ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **id** (string) - Required - The ID of the object. #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. Refer to `ObjectListSchedulesParams` for details. ``` -------------------------------- ### List Subscriptions for an Object Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieve a paginated list of subscriptions for a specific object. Filtering and sorting are available via parameters. ```python client.objects.list_subscriptions(collection, object_id, **params) ``` -------------------------------- ### Set User Channel Data (Slack) Source: https://context7.com/knocklabs/knock-python/llms.txt Configures Slack notification channel data for a user, including access tokens and channel IDs. ```python from knockapi import Knock client = Knock() # Set Slack channel data channel_data = client.users.set_channel_data( user_id="user_123", channel_id="slack-notifications", data={ "connections": [ { "access_token": "xoxb-slack-token", "channel_id": "C0123456789", } ], }, ) ``` -------------------------------- ### Trigger a Workflow (Synchronous) Source: https://github.com/knocklabs/knock-python/blob/main/README.md Use the synchronous client to trigger a workflow. Ensure the KNOCK_API_KEY environment variable is set. ```python import os from knockapi import Knock client = Knock( api_key=os.environ.get("KNOCK_API_KEY"), # This is the default and can be omitted ) response = client.workflows.trigger( key="dinosaurs-loose", recipients=["dnedry"], data={"dinosaur": "triceratops"}, ) print(response.workflow_run_id) ``` -------------------------------- ### Accessing Raw Response Data Source: https://github.com/knocklabs/knock-python/blob/main/README.md Shows how to access the raw HTTP response, including headers, by prefixing method calls with `.with_raw_response.`. ```APIDOC ### Accessing raw response data (e.g. headers) The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., ```python from knockapi import Knock client = Knock() response = client.users.with_raw_response.get( "dnedry", ) print(response.headers.get('X-My-Header')) user = response.parse() # get the object that `users.get()` would have returned print(user.id) ``` These methods return an [`APIResponse`](https://github.com/knocklabs/knock-python/tree/main/src/knockapi/_response.py) object. The async client returns an [`AsyncAPIResponse`](https://github.com/knocklabs/knock-python/tree/main/src/knockapi/_response.py) with the same structure, the only difference being `await`able methods for reading the response content. ``` -------------------------------- ### List Object Preferences Source: https://github.com/knocklabs/knock-python/blob/main/api.md Retrieves a list of all preference sets associated with a specific object. ```APIDOC ## GET /v1/objects/{collection}/{object_id}/preferences ### Description Retrieves a list of all preference sets associated with a specific object. ### Method GET ### Endpoint /v1/objects/{collection}/{object_id}/preferences ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name. - **object_id** (string) - Required - The ID of the object. ```