### Install postgrid-python Source: https://context7.com/postgrid/postgrid-python/llms.txt Install the library from PyPI. Optionally install with the `aiohttp` extra for improved async performance. ```sh pip install postgrid-python ``` ```sh pip install postgrid-python[aiohttp] ``` -------------------------------- ### Add and Run Examples Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Add new examples to the 'examples/' directory and make them executable. Run them against your API. ```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 ``` -------------------------------- ### Install from Wheel File Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Install the Postgrid Python SDK efficiently using a generated wheel file. ```sh $ pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install from Git Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Install the Postgrid Python SDK directly from its Git repository using pip. ```sh $ pip install git+ssh://git@github.com/postgrid/postgrid-python.git ``` -------------------------------- ### Install PostGrid Python Library Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Install the PostGrid Python library using pip. ```sh pip install postgrid-python ``` -------------------------------- ### Install PostGrid with aiohttp support Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Install the PostGrid Python library with aiohttp support for improved concurrency. ```sh pip install postgrid-python[aiohttp] ``` -------------------------------- ### Enable Logging and Check SDK Version Source: https://context7.com/postgrid/postgrid-python/llms.txt Shows how to enable debug or info logging for the PostGrid SDK by setting the `POSTGRID_LOG` environment variable. Also demonstrates how to check the installed SDK version. ```python import os os.environ["POSTGRID_LOG"] = "debug" # or "info" from postgrid import PostGrid client = PostGrid() # Check library version at runtime import postgrid print(postgrid.__version__) # e.g. "2.1.1" ``` -------------------------------- ### Manage Sub-Organizations Source: https://context7.com/postgrid/postgrid-python/llms.txt Provides examples for listing, retrieving, and updating sub-organizations and their users. Ensure you have the necessary permissions to manage these resources. ```python from postgrid import PostGrid client = PostGrid() # List all sub-organizations for sub_org in client.print_mail.sub_organizations.list(limit=20): print(sub_org.id, sub_org.name) # Retrieve a sub-org sub_org = client.print_mail.sub_organizations.retrieve("suborg_abc") print(sub_org.email_preferences) # Retrieve users in a sub-org users_response = client.print_mail.sub_organizations.retrieve_users( "suborg_abc", limit=50, ) print(users_response.data) # Update sub-org settings client.print_mail.sub_organizations.update( email_preferences={"order_notifications": True}, ) ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Install development dependencies using pip if you are not using Rye. Ensure the Python version in .python-version is met. ```sh $ pip install -r requirements-dev.lock ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Use this command to synchronize all project dependencies after installing Rye manually. ```sh $ rye sync --all-features ``` -------------------------------- ### Determine Installed Postgrid Version Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Use this snippet to check the version of the Postgrid package currently active in your Python environment. Ensure the 'postgrid' library is installed. ```python import postgrid print(postgrid.__version__) ``` -------------------------------- ### Create and Send a Postcard Source: https://context7.com/postgrid/postgrid-python/llms.txt Creates a physical postcard with HTML content for both front and back sides. Supports standard postcard sizes and multiple mailing classes. Includes examples for listing postcards and retrieving their preview URLs. ```python from postgrid import PostGrid client = PostGrid() postcard = client.print_mail.postcards.create( to={ "first_name": "Alice", "last_name": "Brown", "address_line1": "456 Oak Ave", "city": "Chicago", "province_or_state": "IL", "postal_or_zip": "60601", "country_code": "US", }, from_={ "company_name": "Acme Corp", "address_line1": "350 Fifth Ave", "city": "New York", "province_or_state": "NY", "postal_or_zip": "10118", "country_code": "US", }, front_html="

Hello {{firstName}}!

", back_html="

Visit us at acme.com

", size="6x4", merge_variables={"firstName": "Alice"}, mailing_class="first_class", description="Summer promo postcard", ) print(postcard.id) print(postcard.status) # List postcards with pagination for pc in client.print_mail.postcards.list(limit=100): print(pc.id, pc.status) # Get preview URL url_resp = client.print_mail.postcards.retrieve_url(postcard.id) print(url_resp.url) ``` -------------------------------- ### Iterate through paginated list Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Example of using the auto-paginating iterator for list methods in the PostGrid API. ```python from postgrid import PostGrid client = PostGrid() all_letters = [] ``` -------------------------------- ### client.print_mail.cheques.retrieve_url Source: https://context7.com/postgrid/postgrid-python/llms.txt Gets the preview URL for a specific cheque. ```APIDOC ## `client.print_mail.cheques.retrieve_url` — Get Cheque Preview URL ### Description Gets the preview URL for a specific cheque. ### Method ```python client.print_mail.cheques.retrieve_url(cheque_id) ``` ### Parameters #### Path Parameters - **cheque_id** (string) - Required - The ID of the cheque to retrieve the preview URL for. ### Response #### Success Response (200) - **url** (string) - The hosted preview URL for the cheque. ``` -------------------------------- ### Initialize PostGrid Clients Source: https://context7.com/postgrid/postgrid-python/llms.txt Instantiate synchronous or asynchronous clients. API keys are inferred from environment variables by default. Custom timeouts and retry configurations can be provided. ```python import os from postgrid import PostGrid, AsyncPostGrid, DefaultHttpxClient, DefaultAioHttpClient # Synchronous client (reads POSTGRID_PRINT_MAIL_API_KEY and POSTGRID_ADDRESS_VERIFICATION_API_KEY) client = PostGrid() # Explicit keys + custom timeout + retry config client = PostGrid( print_mail_api_key="live_pm_...", address_verification_api_key="live_av_...", timeout=30.0, max_retries=3, ) ``` ```python import asyncio from postgrid import AsyncPostGrid, DefaultAioHttpClient async def main(): async with AsyncPostGrid( print_mail_api_key=os.environ["POSTGRID_PRINT_MAIL_API_KEY"], http_client=DefaultAioHttpClient(), ) as client: contact = await client.print_mail.contacts.create( address_line1="123 Main St", city="Toronto", province_or_state="ON", postal_or_zip="M5H 2N2", country_code="CA", first_name="Jane", last_name="Doe", ) print(contact.id) asyncio.run(main()) ``` -------------------------------- ### Create Report Sample Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Generates a sample for a report. ```python client.print_mail.reports.sample(**params) ``` -------------------------------- ### client.print_mail.postcards.retrieve_url Source: https://context7.com/postgrid/postgrid-python/llms.txt Gets the preview URL for a specific postcard. ```APIDOC ## `client.print_mail.postcards.retrieve_url` — Get Postcard Preview URL ### Description Gets the preview URL for a specific postcard. ### Method ```python client.print_mail.postcards.retrieve_url(postcard_id) ``` ### Parameters #### Path Parameters - **postcard_id** (string) - Required - The ID of the postcard to retrieve the preview URL for. ### Response #### Success Response (200) - **url** (string) - The hosted preview URL for the postcard. ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment with the expected Python version using Rye. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### Retrieve Letter URL Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Gets the URL for a specific letter. ```python client.print_mail.letters.retrieve_url(id) ``` -------------------------------- ### Create Report Sample Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Adds a sample to a specific report. ```python client.print_mail.reports.samples.create(id, **params) ``` -------------------------------- ### Retrieve Cheque URL Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Gets the URL for a specific cheque. ```python client.print_mail.cheques.retrieve_url(id) ``` -------------------------------- ### Retrieve Postcard URL Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Gets a URL to access a specific postcard. ```python client.print_mail.postcards.retrieve_url(id) ``` -------------------------------- ### Build Distribution Files Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Build the source and wheel files for the Postgrid Python library using Rye or the Python build module. ```sh $ rye build # or $ python -m build ``` -------------------------------- ### Enabling Logging Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Explains how to enable logging for the PostGrid client library. ```APIDOC ## Logging ### Description Enables logging for the PostGrid library using Python's standard `logging` module. ### Configuration Set the environment variable `POSTGRID_LOG` to `info` for general logging, or `debug` for more verbose output. ### Usage ```shell $ export POSTGRID_LOG=info ``` Or: ```shell $ export POSTGRID_LOG=debug ``` ``` -------------------------------- ### Template Retrieve Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Retrieves a Template by its ID. Use this to get details of a specific template. ```APIDOC ## GET /print-mail/v1/templates/{id} ### Description Retrieves a Template by its ID. ### Method GET ### Endpoint /print-mail/v1/templates/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Template to retrieve. ### Request Example ```python client.print_mail.templates.retrieve(id) ``` ### Response #### Success Response (200) - **Template** (object) - The requested Template object. ``` -------------------------------- ### Run Tests Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Execute the test suite for the Postgrid Python SDK using the provided script. ```sh $ ./scripts/test ``` -------------------------------- ### SelfMailer Retrieve Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Retrieves a SelfMailer by its ID. Use this to get details of a specific SelfMailer. ```APIDOC ## GET /print-mail/v1/self_mailers/{id} ### Description Retrieves a SelfMailer by its ID. ### Method GET ### Endpoint /print-mail/v1/self_mailers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the SelfMailer to retrieve. ### Request Example ```python client.print_mail.self_mailers.retrieve(id) ``` ### Response #### Success Response (200) - **SelfMailer** (object) - The requested SelfMailer object. ``` -------------------------------- ### Asynchronous Client with aiohttp Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Instantiate the asynchronous PostGrid client using `AsyncPostGrid` with `DefaultAioHttpClient` for improved concurrency. API keys are typically loaded from environment variables. ```python import os import asyncio from postgrid import DefaultAioHttpClient from postgrid import AsyncPostGrid async def main() -> None: async with AsyncPostGrid( print_mail_api_key=os.environ.get( "POSTGRID_PRINT_MAIL_API_KEY" ), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: contact = await client.print_mail.contacts.create( address_line1="addressLine1", country_code="countryCode", first_name="firstName", ) print(contact.id) asyncio.run(main()) ``` -------------------------------- ### Configure PostGrid HTTP Client with Proxies and Transports Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Customize the underlying `httpx` client by passing a `DefaultHttpxClient` instance to the `PostGrid` constructor. This allows for advanced configurations like proxies and custom transports. ```python import httpx from postgrid import PostGrid, DefaultHttpxClient client = PostGrid( # Or use the `POSTGRID_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Asynchronous Client Usage Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Instantiate the asynchronous PostGrid client using `AsyncPostGrid` and `await` API calls. API keys are typically loaded from environment variables. ```python import os import asyncio from postgrid import AsyncPostGrid client = AsyncPostGrid( print_mail_api_key=os.environ.get( "POSTGRID_PRINT_MAIL_API_KEY" ), # This is the default and can be omitted ) async def main() -> None: contact = await client.print_mail.contacts.create( address_line1="addressLine1", country_code="countryCode", first_name="firstName", ) print(contact.id) asyncio.run(main()) ``` -------------------------------- ### Create, Sample, and Export Mail Reports Source: https://context7.com/postgrid/postgrid-python/llms.txt Demonstrates creating analytics reports, generating samples, and exporting report data to CSV. Ensure the report ID is available for subsequent operations. ```python from postgrid import PostGrid client = PostGrid() # Create a report report = client.print_mail.reports.create( type="letters", description="Q1 2025 Letter Report", filters={"status": "mailed"}, ) print(report.id) # Generate a sample of the report sample = client.print_mail.reports.sample( report_id=report.id, count=10, ) print(sample.data) # Create an export (CSV) export = client.print_mail.reports.exports.create( report_id=report.id, file_format="csv", ) print(export.id) print(export.url) # download URL when ready # Retrieve export status export_status = client.print_mail.reports.exports.retrieve( export_id=export.id, report_id=report.id, ) print(export_status.status) ``` -------------------------------- ### Import Report Sample Types Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Import necessary types for working with Report Samples. ```python from postgrid.types.print_mail.reports import ReportSample, ReportSampleCreateBase ``` -------------------------------- ### Pagination Source: https://context7.com/postgrid/postgrid-python/llms.txt Demonstrates how to handle pagination for list endpoints using auto-paginating iterators and manual page controls. ```APIDOC ## Pagination with Auto-Iterators ### Description List endpoints return auto-paginating iterators, simplifying the retrieval of all items. ### Method GET ### Endpoint /v1/print_mail/letters ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of items to retrieve per page. ### Request Example ```python # Synchronous auto-pagination client = PostGrid() all_letters = [] for letter in client.print_mail.letters.list(limit=100): all_letters.append(letter) print(f"Total letters: {len(all_letters)}") # Async auto-pagination async_client = AsyncPostGrid() async def fetch_all(): results = [] async for contact in async_client.print_mail.contacts.list(limit=50): results.append(contact) return results contacts = asyncio.run(fetch_all()) ``` ``` ```APIDOC ## Manual Pagination ### Description Manually control pagination by fetching pages and retrieving the next page. ### Method GET ### Endpoint /v1/print_mail/letters ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of items to retrieve per page. ### Request Example ```python page = client.print_mail.letters.list(limit=10) print([l.id for l in page.data]) while page.has_next_page(): page = page.get_next_page() print([l.id for l in page.data]) ``` ``` -------------------------------- ### Verifying an Address with Nested Parameters Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Demonstrates how to use nested parameters, specifically a dictionary typed using `TypedDict`, for the address verification endpoint. Ensure all required address fields are provided. ```python from postgrid import PostGrid client = PostGrid() response = client.address_verification.verify( address={ "city": "city", "country": "ca", "line1": "line1", "postal_or_zip": "postalOrZip", "province_or_state": "provinceOrState", }, ) print(response.address) ``` -------------------------------- ### Synchronous Client Usage Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Instantiate the synchronous PostGrid client and create a contact. API keys are typically loaded from environment variables. ```python import os from postgrid import PostGrid client = PostGrid( print_mail_api_key=os.environ.get( "POSTGRID_PRINT_MAIL_API_KEY" ), # This is the default and can be omitted ) contact = client.print_mail.contacts.create( address_line1="addressLine1", country_code="countryCode", first_name="firstName", ) print(contact.id) ``` -------------------------------- ### Manage and Send Campaigns Source: https://context7.com/postgrid/postgrid-python/llms.txt This snippet covers creating, updating, sending, listing, and deleting mail campaigns. Campaigns target a mailing list and use order profiles for mail configuration. Ensure `mlist_abc` and `lprofile_abc` are valid IDs. ```python from postgrid import PostGrid client = PostGrid() # Create a campaign campaign = client.print_mail.campaigns.create( mailing_list="mlist_abc", letter_profile="lprofile_abc", description="Spring 2025 Campaign", send_date="2025-04-01", metadata={"campaign_code": "SP25"}, ) print(campaign.id) print(campaign.status) # "draft" # Update campaign before sending campaign = client.print_mail.campaigns.update( campaign.id, description="Spring 2025 Campaign (Final)", send_date="2025-04-05", ) # Send the campaign immediately sent = client.print_mail.campaigns.send(campaign.id) print(sent.status) # "sending" # List all campaigns for c in client.print_mail.campaigns.list(limit=50): print(c.id, c.status) # Delete (cancel) a campaign client.print_mail.campaigns.delete(campaign.id) ``` -------------------------------- ### Handle Pagination for List Endpoints Source: https://context7.com/postgrid/postgrid-python/llms.txt Illustrates both synchronous and asynchronous auto-pagination using for-loops and manual page controls. For async operations, ensure an event loop is running. ```python import asyncio from postgrid import PostGrid, AsyncPostGrid # Synchronous auto-pagination client = PostGrid() all_letters = [] for letter in client.print_mail.letters.list(limit=100): all_letters.append(letter) print(f"Total letters: {len(all_letters)}") # Manual pagination with page controls page = client.print_mail.letters.list(limit=10) print([l.id for l in page.data]) while page.has_next_page(): page = page.get_next_page() print([l.id for l in page.data]) # Async auto-pagination async_client = AsyncPostGrid() async def fetch_all(): results = [] async for contact in async_client.print_mail.contacts.list(limit=50): results.append(contact) return results contacts = asyncio.run(fetch_all()) ``` -------------------------------- ### Address Verification with Nested Parameters Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Shows how to use the `address_verification.verify` method with nested dictionary parameters. ```APIDOC ## Address Verification with Nested Parameters ### Description Verifies an address using nested parameters, where the `address` parameter is a dictionary. ### Method `client.address_verification.verify()` ### Parameters - **address** (dict) - Required - A dictionary containing address details. - **city** (str) - Required - The city name. - **country** (str) - Required - The country code (e.g., 'ca'). - **line1** (str) - Required - The first line of the address. - **postal_or_zip** (str) - Required - The postal or ZIP code. - **province_or_state** (str) - Required - The province or state. ### Request Example ```python from postgrid import PostGrid client = PostGrid() response = client.address_verification.verify( address={ "city": "city", "country": "ca", "line1": "line1", "postal_or_zip": "postalOrZip", "province_or_state": "provinceOrState", }, ) print(response.address) ``` ``` -------------------------------- ### Configuring Timeouts Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Details how to set request timeouts for the client. ```APIDOC ## Timeouts ### Description Configures the maximum time to wait for a response from the API. ### Default Behavior Requests time out after 1 minute by default. ### Configuration - **`timeout`**: Accepts a float (seconds) or an `httpx.Timeout` object for more granular control. ### Request Example ```python from postgrid import PostGrid import httpx # Configure the default for all requests: client = PostGrid( # 20 seconds (default is 1 minute) timeout=20.0, ) # More granular control: client = PostGrid( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # Override per-request: client.with_options(timeout=5.0).address_verification.verify( address="address", ) ``` **Note**: Requests that time out are retried twice by default. ``` -------------------------------- ### Publish to PyPI Manually Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Manually release a package to PyPI by running the publish script with a PYPI_TOKEN set in the environment. ```sh bin/publish-pypi ``` -------------------------------- ### Report Samples Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Methods for creating samples for reports. ```APIDOC ## POST /print-mail/v1/reports/{id}/samples ### Description Creates a sample for a specific report. ### Method POST ### Endpoint /print-mail/v1/reports/{id}/samples ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the report. #### Request Body - **params** (object) - Required - Parameters for creating the sample. ### Request Example ```python client.print_mail.reports.samples.create(id, **params) ``` ### Response #### Success Response (200) - **ReportSample** (object) - Details of the created report sample. ``` -------------------------------- ### Create Report Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Generates a new report based on provided parameters. ```python client.print_mail.reports.create(**params) ``` -------------------------------- ### Create Report Export Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Initiates an export for a specific report. ```python client.print_mail.reports.exports.create(report_id, **params) ``` -------------------------------- ### Manage HTTP Resources with PostGrid Client Context Manager Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Use the `PostGrid` client as a context manager (`with PostGrid() as client:`) to ensure that underlying HTTP connections are reliably closed upon exiting the block, preventing resource leaks. ```python from postgrid import PostGrid with PostGrid() as client: # make requests here ... ``` -------------------------------- ### List Letters (Synchronous) Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Demonstrates how to list letters using the synchronous client, automatically fetching more pages as needed. ```APIDOC ## List Letters (Synchronous) ### Description Fetches a list of letters, automatically handling pagination. ### Method `client.print_mail.letters.list()` ### Parameters - **limit** (int) - Optional - The maximum number of items to return per page. ### Request Example ```python from postgrid import PostGrid client = PostGrid() all_letters = [] for letter in client.print_mail.letters.list( limit=100, ): all_letters.append(letter) print(all_letters) ``` ``` -------------------------------- ### Create Mailing List Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Creates a new mailing list with the provided parameters. ```python from postgrid.types.print_mail import MailingList, MailingListUpdate, MailingListDeleteResponse # Example usage: # client.print_mail.mailing_lists.create(**params) ``` -------------------------------- ### Logging and Debugging Source: https://context7.com/postgrid/postgrid-python/llms.txt Enable request/response logging and check the library version. ```APIDOC ## Enabling Logging ### Description Enable detailed logging of requests and responses by setting the `POSTGRID_LOG` environment variable. ### Environment Variable - **POSTGRID_LOG** (string) - Set to "debug" for detailed logs or "info" for general information. ### Request Example ```python import os os.environ["POSTGRID_LOG"] = "debug" from postgrid import PostGrid client = PostGrid() ``` ``` ```APIDOC ## Checking Library Version ### Description Retrieve the currently installed version of the PostGrid library. ### Request Example ```python import postgrid print(postgrid.__version__) # e.g. "2.1.1" ``` ``` -------------------------------- ### client.print_mail.bank_accounts.list Source: https://context7.com/postgrid/postgrid-python/llms.txt Lists all created bank accounts. ```APIDOC ## `client.print_mail.bank_accounts.list` — List Bank Accounts ### Description Lists all created bank accounts. ### Method ```python client.print_mail.bank_accounts.list(limit=20) ``` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of bank accounts to return per page. ### Response #### Success Response (200) - **data** (array) - An array of bank account objects. - **id** (string) - The unique identifier for the bank account. - **bank_name** (string) - The name of the bank. ``` -------------------------------- ### Manage Mailing Lists and Trigger Jobs Source: https://context7.com/postgrid/postgrid-python/llms.txt This snippet demonstrates creating, updating, and deleting mailing lists, as well as triggering mail jobs against them for bulk sending. Ensure you have a valid `letter_profile` or `postcard_profile` ID. ```python from postgrid import PostGrid client = PostGrid() # Create a mailing list mailing_list = client.print_mail.mailing_lists.create( description="Q1 2025 Newsletter Recipients", metadata={"segment": "premium_customers"}, ) print(mailing_list.id) # Update list metadata updated = client.print_mail.mailing_lists.update( mailing_list.id, description="Q1 2025 Newsletter Recipients (Updated)", ) # Trigger a mailing job against the list job = client.print_mail.mailing_lists.jobs( mailing_list.id, letter_profile="lprofile_abc", # or postcard_profile, etc. send_date="2025-02-15", ) print(job.id) # Delete list client.print_mail.mailing_lists.delete(mailing_list.id) ``` -------------------------------- ### Create Cheque - Python Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Use the create method to generate a new cheque. Pass parameters as a dictionary. ```python client.print_mail.order_profiles.cheques.create(**params) -> ChequeProfile ``` -------------------------------- ### Manage Contacts: Retrieve, List, and Delete Source: https://context7.com/postgrid/postgrid-python/llms.txt This section covers retrieving a specific contact by ID, listing contacts with search and pagination options, and deleting contacts. Ensure you have the PostGrid client initialized. ```python from postgrid import PostGrid client = PostGrid() # Retrieve by ID contact = client.print_mail.contacts.retrieve("contact_xyz") print(contact.first_name, contact.address_line1) ``` ```python # List contacts with search and auto-pagination all_contacts = [] for contact in client.print_mail.contacts.list(limit=50, search='"New York"'): all_contacts.append(contact) print(f"Found {len(all_contacts)} contacts") ``` ```python # Manual page-by-page page = client.print_mail.contacts.list(limit=10) print([c.id for c in page.data]) if page.has_next_page(): next_page = page.get_next_page() print([c.id for c in next_page.data]) ``` ```python # Delete result = client.print_mail.contacts.delete("contact_xyz") print(result.deleted) # True ``` -------------------------------- ### List Letters (Asynchronous) Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Demonstrates how to list letters using the asynchronous client, iterating through items across all pages. ```APIDOC ## List Letters (Asynchronous) ### Description Fetches a list of letters asynchronously, iterating through items across all pages. ### Method `client.print_mail.letters.list()` ### Parameters - **limit** (int) - Optional - The maximum number of items to return per page. ### Request Example ```python import asyncio from postgrid import AsyncPostGrid client = AsyncPostGrid() async def main() -> None: all_letters = [] async for letter in client.print_mail.letters.list( limit=100, ): all_letters.append(letter) print(all_letters) asyncio.run(main()) ``` ``` -------------------------------- ### Create a Contact Source: https://context7.com/postgrid/postgrid-python/llms.txt Creates a mailing contact. Automatic address verification is performed if a live API key is used. Requires either `first_name` or `company_name`. Duplicate contacts are automatically deduplicated. ```python from postgrid import PostGrid client = PostGrid() ``` -------------------------------- ### Create Postcard Order Profile Source: https://context7.com/postgrid/postgrid-python/llms.txt This snippet demonstrates creating a postcard order profile, defining front and back HTML content, size, sender, and mailing class. Ensure `contact_sender_id` is a valid sender ID. ```python from postgrid import PostGrid client = PostGrid() # Create a postcard order profile postcard_profile = client.print_mail.order_profiles.postcards.create( front_html="

Hello {{firstName}}!

", back_html="

Visit acme.com

", size="6x4", from_="contact_sender_id", mailing_class="standard_class", ) print(postcard_profile.id) ``` -------------------------------- ### Create and Retrieve a Self-Mailer Source: https://context7.com/postgrid/postgrid-python/llms.txt Use this to create a self-mailer with HTML content for inside and outside panels. After creation, you can retrieve a URL to track its status. ```python from postgrid import PostGrid client = PostGrid() self_mailer = client.print_mail.self_mailers.create( to={ "first_name": "Carol", "last_name": "White", "address_line1": "321 Elm St", "city": "Austin", "province_or_state": "TX", "postal_or_zip": "78701", "country_code": "US", }, from_={ "company_name": "Acme Corp", "address_line1": "350 Fifth Ave", "city": "New York", "province_or_state": "NY", "postal_or_zip": "10118", "country_code": "US", }, inside_html="

Special Offer Inside!

Save 20% this month.

", outside_html="

Acme Corp — Your Trusted Partner

", size="6x18_bifold", mailing_class="standard_class", ) print(self_mailer.id) url_resp = client.print_mail.self_mailers.retrieve_url(self_mailer.id) print(url_resp.url) ``` -------------------------------- ### Create and Send a Cheque Source: https://context7.com/postgrid/postgrid-python/llms.txt Creates a physical cheque for printing and delivery, using a previously created bank account. Supports retrieving a deposit-ready PDF and a preview URL. Ensure the bank account is created first. ```python from postgrid import PostGrid client = PostGrid() # First create a bank account bank_account = client.print_mail.bank_accounts.create( bank_name="First National Bank", account_number="123456789", routing_number="021000021", signatory_name="John Smith", country_code="US", ) # Create a cheque cheque = client.print_mail.cheques.create( to={ "first_name": "Bob", "last_name": "Jones", "address_line1": "789 Pine Rd", "city": "Seattle", "province_or_state": "WA", "postal_or_zip": "98101", "country_code": "US", }, from_={ "company_name": "Acme Corp", "address_line1": "350 Fifth Ave", "city": "New York", "province_or_state": "NY", "postal_or_zip": "10118", "country_code": "US", }, bank_account=bank_account.id, amount=15000, # in cents number=1001, memo="Invoice #1001 payment", message="Thank you for your business.", ) print(cheque.id) # Retrieve deposit-ready PDF cheque_with_pdf = client.print_mail.cheques.retrieve_with_deposit_ready_pdf(cheque.id) # Get cheque preview URL url_resp = client.print_mail.cheques.retrieve_url(cheque.id) print(url_resp.url) ``` -------------------------------- ### Accessing Raw Data Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Demonstrates how to work directly with the `data` attribute of the response object. ```APIDOC ## Accessing Raw Data ### Description Allows direct access to the list of items returned in the response data. ### Request Example ```python # Assuming 'client' is an instance of AsyncPostGrid first_page = await client.print_mail.letters.list( limit=100, ) for letter in first_page.data: print(letter.id) # For non-async usage, remove `await` keyword. ``` ``` -------------------------------- ### Manual Pagination Control Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Provides granular control over pagination using `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods. Useful when you need to inspect or control when the next page is fetched. ```python first_page = await client.print_mail.letters.list( limit=100, ) 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.data)}") # Remove `await` for non-async usage. ``` -------------------------------- ### Import Cheque Types Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Import necessary types for working with cheques. ```python from postgrid.types.print_mail import Cheque, ChequeSize, DigitalOnly, ChequeRetrieveURLResponse ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/postgrid/postgrid-python/blob/main/CONTRIBUTING.md Activate the virtual environment to run Python scripts without the 'rye run' prefix. ```sh # Activate the virtual environment - https://docs.python.org/3/library/venv.html#how-venvs-work $ source .venv/bin/activate ``` -------------------------------- ### Template List Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Lists all Templates. Supports filtering and pagination through parameters. ```APIDOC ## GET /print-mail/v1/templates ### Description Lists all Templates. ### Method GET ### Endpoint /print-mail/v1/templates ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for listing Templates. ### Request Example ```python client.print_mail.templates.list(**params) ``` ### Response #### Success Response (200) - **SyncSkipLimit[Template]** (object) - A list of Template objects. ``` -------------------------------- ### Manual Pagination Control Source: https://github.com/postgrid/postgrid-python/blob/main/README.md Shows how to manually control pagination using `.has_next_page()`, `.next_page_info()`, and `.get_next_page()`. ```APIDOC ## Manual Pagination Control ### Description Provides granular control over fetching pages of results. ### Methods - **`has_next_page()`**: Returns `True` if there is a next page of results. - **`next_page_info()`**: Returns information needed to fetch the next page. - **`get_next_page()`**: Fetches the next page of results. ### Request Example ```python # Assuming 'client' is an instance of AsyncPostGrid first_page = await client.print_mail.letters.list( limit=100, ) 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.data)}") # For non-async usage, remove `await` keyword. ``` ``` -------------------------------- ### Import Contact Types Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Import necessary types for working with contacts. ```python from postgrid.types.print_mail import Contact, ContactCreate, ContactDeleteResponse ``` -------------------------------- ### Create Contact Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Use this method to create a new contact. It requires parameters defined in `contact_create_params.py`. ```python client.print_mail.contacts.create(**params) ``` -------------------------------- ### Create Contact Source: https://context7.com/postgrid/postgrid-python/llms.txt Creates a new contact, either individual or company, with address details and optional metadata. ```APIDOC ## client.print_mail.contacts.create ### Description Creates a new contact with provided details. ### Method POST ### Endpoint /v1/contacts ### Parameters #### Request Body - **first_name** (string) - Optional - The first name of the contact. - **last_name** (string) - Optional - The last name of the contact. - **company_name** (string) - Optional - The company name for a business contact. - **address_line1** (string) - Required - The first line of the address. - **address_line2** (string) - Optional - The second line of the address. - **city** (string) - Required - The city of the address. - **province_or_state** (string) - Required - The state or province. - **postal_or_zip** (string) - Required - The postal or ZIP code. - **country_code** (string) - Required - The ISO 3166-1 alpha-2 country code. - **email** (string) - Optional - The email address of the contact. - **metadata** (object) - Optional - Key-value pairs for additional information. ### Request Example ```json { "first_name": "John", "last_name": "Smith", "address_line1": "350 Fifth Ave", "city": "New York", "province_or_state": "NY", "postal_or_zip": "10118", "country_code": "US", "email": "john.smith@example.com", "metadata": {"customer_id": "cust_abc123"} } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the created contact. - **address_status** (string) - The verification status of the address ('verified', 'unverified', 'failed'). ### Response Example ```json { "id": "contact_xyz...", "address_status": "verified" } ``` ``` -------------------------------- ### Create Individual and Company Contacts Source: https://context7.com/postgrid/postgrid-python/llms.txt Use this to create new contacts in your address book. Individual contacts require a first and last name, while company contacts only need a company name. ```python contact = client.print_mail.contacts.create( first_name="John", last_name="Smith", address_line1="350 Fifth Ave", city="New York", province_or_state="NY", postal_or_zip="10118", country_code="US", email="john.smith@example.com", metadata={"customer_id": "cust_abc123"}, ) print(contact.id) print(contact.address_status) ``` ```python company = client.print_mail.contacts.create( company_name="Acme Corp", address_line1="1600 Amphitheatre Pkwy", city="Mountain View", province_or_state="CA", postal_or_zip="94043", country_code="US", ) print(company.id) ``` -------------------------------- ### Import Postcard Types Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Import necessary types for working with Postcard order profiles. ```python from postgrid.types.print_mail.order_profiles import ( PostcardProfile, PostcardSize, PostcardDeleteResponse, ) ``` -------------------------------- ### Manage HTML Templates Source: https://context7.com/postgrid/postgrid-python/llms.txt Operations to create, update, list, and delete reusable HTML templates for mailings. ```APIDOC ## client.print_mail.templates.create / update / list / delete ### Description Manage reusable HTML templates that support merge variables. ### Method POST (create), PUT (update), GET (list), DELETE (delete) ### Endpoint /v1/templates (create, list), /v1/templates/{template_id} (update, delete) ### Parameters #### Request Body (create, update) - **html** (string) - Required - The HTML content of the template, supporting merge variables like `{{variableName}}`. - **description** (string) - Optional - A description for the template. - **metadata** (object) - Optional - Key-value pairs for additional information. #### Path Parameters (update, delete) - **template_id** (string) - Required - The ID of the template to update or delete. #### Query Parameters (list) - **limit** (integer) - Optional - The maximum number of templates to return per page. ### Request Example (create) ```python client.print_mail.templates.create( html="

Dear {{firstName}},

{{body}}

", description="Monthly newsletter template", metadata={"department": "marketing"} ) ``` ### Request Example (update) ```python client.print_mail.templates.update( template_id, html="

Hello {{firstName}}!

{{body}}

", description="Updated newsletter template v2" ) ``` ### Request Example (list) ```python client.print_mail.templates.list(limit=20) ``` ### Request Example (delete) ```python client.print_mail.templates.delete(template_id) ``` ### Response (create, update) #### Success Response (201 or 200) - **id** (string) - The unique identifier for the template. ### Response Example (create, update) ```json { "id": "template_abc..." } ``` ### Response (list) #### Success Response (200) - **data** (array) - A list of template objects. ### Response Example (list) ```json { "data": [ { "id": "template_abc...", "description": "Monthly newsletter template" } ] } ``` ``` -------------------------------- ### client.print_mail.mailing_lists.* Source: https://context7.com/postgrid/postgrid-python/llms.txt Manages mailing lists, allowing for creation from imported contacts and triggering mail jobs for bulk sending. ```APIDOC ## `client.print_mail.mailing_lists.create` / `jobs` — Manage Mailing Lists Create mailing lists from imported contacts and trigger mail jobs against them for bulk sending. ### Operations - **create**: Creates a new mailing list. - **update**: Updates an existing mailing list. - **jobs**: Triggers a mail job against a mailing list. - **delete**: Deletes a mailing list. ### `create` Parameters - **description** (string) - Optional - A description for the mailing list. - **metadata** (object) - Optional - Key-value pairs for additional metadata. ### `jobs` Parameters - **mailing_list_id** (string) - Required - The ID of the mailing list. - **letter_profile** (string) - Optional - The ID of the letter profile to use. - **postcard_profile** (string) - Optional - The ID of the postcard profile to use. - **send_date** (string) - Optional - The date to send the mail job. ### `update` Parameters - **mailing_list_id** (string) - Required - The ID of the mailing list to update. - **description** (string) - Optional - The updated description for the mailing list. ### `delete` Parameters - **mailing_list_id** (string) - Required - The ID of the mailing list to delete. ### Request Example (Create and Job) ```python from postgrid import PostGrid client = PostGrid() # Create a mailing list mailing_list = client.print_mail.mailing_lists.create( description="Q1 2025 Newsletter Recipients", metadata={"segment": "premium_customers"}, ) print(mailing_list.id) # Update list metadata updated = client.print_mail.mailing_lists.update( mailing_list.id, description="Q1 2025 Newsletter Recipients (Updated)", ) # Trigger a mailing job against the list job = client.print_mail.mailing_lists.jobs( mailing_list.id, letter_profile="lprofile_abc", # or postcard_profile, etc. send_date="2025-02-15", ) print(job.id) # Delete list client.print_mail.mailing_lists.delete(mailing_list.id) ``` ### Response (Create) #### Success Response (200) - **id** (string) - The unique identifier for the created mailing list. ### Response (Jobs) #### Success Response (200) - **id** (string) - The unique identifier for the mail job. ### Response (Update) #### Success Response (200) - **id** (string) - The unique identifier for the updated mailing list. - **description** (string) - The updated description of the mailing list. ``` -------------------------------- ### Create Mailing List Job Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Initiates a job for a specific mailing list using its ID and job parameters. ```python # Example usage: # client.print_mail.mailing_lists.jobs(id, **params) ``` -------------------------------- ### Import Cheque Types - Python Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Import necessary types for cheque operations, including profile, currency, and response types. ```python from postgrid.types.print_mail.order_profiles import ( ChequeProfile, CurrencyCode, ChequeListResponse, ChequeDeleteResponse, ) ``` -------------------------------- ### Retrieve Cheque with Deposit-Ready PDF Source: https://github.com/postgrid/postgrid-python/blob/main/api.md Fetches a cheque along with a deposit-ready PDF. ```python client.print_mail.cheques.retrieve_with_deposit_ready_pdf(id) ```