### Install plaid-python Source: https://github.com/plaid/plaid-python/blob/master/README.md Install the plaid-python library using pip. This library only supports python3. ```console pip3 install plaid-python ``` -------------------------------- ### Example Request Model Structure Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Illustrates the structure of an example request model, AccountsGetRequest. It defines attributes like access_token, secret, client_id, and options. ```python class AccountsGetRequest(ModelNormal): """ Attributes: access_token (str): The access token associated with the Item secret (str): The client secret client_id (str): The client ID options (AccountsGetRequestOptions): Optional parameters """ ``` -------------------------------- ### Initialize Plaid Client (Pre-8.0.0) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of initializing the Plaid client using the older method before version 8.0.0. ```python from plaid import Client Client( client_id=os.environ['CLIENT_ID'], secret=os.environ['SECRET'], environment='sandbox', api_version="2020-09-14", client_app="plaid-python-unit-tests" ) ``` -------------------------------- ### Account Data Structure Example Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Provides an example of the expected structure for an 'Account' object returned in API responses. It details fields like `account_id`, `name`, `type`, and `balances`. ```python account = response['accounts'][0] { 'account_id': 'string', 'name': 'string', 'mask': 'string', 'type': 'checking' | 'savings' | 'investment' | '...', 'subtype': 'checking' | 'savings' | '...', 'verification_status': 'unverified' | 'verified' | '...', 'balances': { 'available': float, 'current': float, 'limit': float, } } ``` -------------------------------- ### Initialize Plaid Client (8.0.0+) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of initializing the Plaid client using the new method from version 8.0.0 onwards. ```python import plaid from plaid.api import plaid_api configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': client_id, 'secret': secret, 'plaidVersion': '2020-09-14' } ) api_client = plaid.ApiClient(configuration) client = plaid_api.PlaidApi(api_client) ``` -------------------------------- ### Build Docker Image for Tests Source: https://github.com/plaid/plaid-python/blob/master/CONTRIBUTING.md Builds the Docker image required for running client tests. Ensure you have Docker installed. ```bash docker build -t plaid-python . ``` -------------------------------- ### Call Auth Endpoint (Pre-8.0.0) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of calling the Auth endpoint using the older method before version 8.0.0. ```python response = client.Auth.get(access_token) ``` -------------------------------- ### Initialize Plaid API Client Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Initialize the Plaid API client with sandbox environment and API credentials. This setup is required before making any API calls. ```python import plaid from plaid.api import plaid_api # Initialize configuration configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': 'your_client_id', 'secret': 'your_secret', } ) # Create API client api_client = plaid.ApiClient(configuration) client = plaid_api.PlaidApi(api_client) ``` -------------------------------- ### Initialize Plaid Client Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/README.md Initialize the Plaid client with configuration, including the API host environment and authentication credentials (clientId and secret). This setup is necessary before making any API calls. ```python import plaid from plaid.api import plaid_api configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': 'your_client_id', 'secret': 'your_secret', } ) api_client = plaid.ApiClient(configuration) client = plaid_api.PlaidApi(api_client) ``` -------------------------------- ### TransactionsGet with Offset-based Pagination Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Shows how to implement offset-based pagination for older GET endpoints like `TransactionsGetRequest`. ```APIDOC ## TransactionsGet with Offset-based Pagination ### Description This example illustrates offset-based pagination for endpoints that support it, such as `TransactionsGetRequest`. It continues to fetch transactions by incrementing the `offset` until the total number of transactions is reached. ### Method POST ### Endpoint `/transactions/get` ### Parameters #### Request Body - **access_token** (string) - Required - The access token associated with the Item data is being requested for. - **start_date** (date) - Required - The start date in `YYYY-MM-DD` format. - **end_date** (date) - Required - The end date in `YYYY-MM-DD` format. - **options** (TransactionsGetRequestOptions) - Optional - An object containing optional parameters. - **offset** (integer) - Optional - The number of transactions to skip before returning results. ``` -------------------------------- ### Enum Data Types (Pre-8.0.0) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of representing products and country codes as strings before version 8.0.0. ```python 'products': ['auth', 'transactions'], 'country_codes': ['US'], ``` -------------------------------- ### Get Account Information Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve general account information for an item. Requires an access token. ```python from plaid.model.accounts_get_request import AccountsGetRequest request = AccountsGetRequest( access_token=access_token, ) response = client.accounts_get(request) print(f"Item ID: {response['item']['item_id']}") for account in response['accounts']: print(f"{account['name']} - Type: {account['type']}") ``` -------------------------------- ### Sandbox Environment Configuration with API Key Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Example of configuring the Plaid client for the Sandbox environment using your client ID and secret. Ensure you have imported the plaid library. ```python import plaid configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': 'your_client_id', 'secret': 'your_secret', } ) ``` -------------------------------- ### Offset-Based Pagination for TransactionsGet Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Shows how to use offset-based pagination for older GET endpoints, continuing to fetch transactions until the total number of transactions is reached. ```python from plaid.model.transactions_get_request import TransactionsGetRequest from plaid.model.transactions_get_request_options import TransactionsGetRequestOptions while len(transactions) < response['total_transactions']: options = TransactionsGetRequestOptions( offset=len(transactions) ) request = TransactionsGetRequest( access_token=access_token, start_date=date(2020, 1, 1), end_date=date(2021, 1, 1), options=options ) response = client.transactions_get(request) ``` -------------------------------- ### Set Request Timeout (8.0.0+) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of setting a per-request timeout for an API call from version 8.0.0 onwards. ```python response = client.accounts_balance_get(request, _request_timeout=60) ``` -------------------------------- ### Get Real-Time Balance with Plaid Python SDK Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md This snippet demonstrates how to fetch the current real-time balance for user accounts. The required request model must be imported. ```python from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest request = AccountsBalanceGetRequest(access_token=access_token) response = client.accounts_balance_get(request) ``` -------------------------------- ### Get Account Balance Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve real-time balance data for all accounts associated with an item. Requires an access token. ```python from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest request = AccountsBalanceGetRequest( access_token=access_token, ) response = client.accounts_balance_get(request) for account in response['accounts']: print(f"Account: {account['name']}") print(f" Available: {account['balances']['available']}") print(f" Current: {account['balances']['current']}") ``` -------------------------------- ### Transaction Data Structure Example Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Shows the expected structure for a 'Transaction' object. Includes fields such as `transaction_id`, `amount`, `date`, `name`, and `category`. ```python transaction = response['transactions'][0] { 'transaction_id': 'string', 'account_id': 'string', 'amount': float, 'currency_code': 'USD' | '...', 'date': date(2022, 1, 1), 'name': 'string', 'merchant_name': 'string', 'category': ['category', 'subcategory'], 'personal_finance_category': {...}, 'pending': True | False, } ``` -------------------------------- ### Call Auth Endpoint (8.0.0+) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of calling the Auth endpoint using the new method from version 8.0.0 onwards, including request model. ```python import plaid from plaid.model.auth_get_request import AuthGetRequest from plaid.model.auth_get_request_options import AuthGetRequestOptions ag_request = AuthGetRequest( access_token=access_token ) response = client.auth_get(ag_request) ``` -------------------------------- ### Get Business Verification Details Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve the status and details of a business verification. Requires the business verification ID. ```python client.business_verification_get(business_verification_get_request=BusinessVerificationGetRequest(business_verification_id=business_verification_id)) ``` -------------------------------- ### Plaid API Exception Handling Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Details the unified error handling model using `plaid.ApiException` and provides examples of catching and inspecting API errors. ```APIDOC ## Plaid API Exception Handling ### Description The Plaid Python SDK uses a unified error handling mechanism based on `plaid.ApiException`. This allows you to catch potential errors during API calls and inspect the error details, such as the error code and message, to implement appropriate error handling logic. ### Exception Handling ```python import plaid import json try: # ... make an API call that might fail ... pass except plaid.ApiException as e: response_body = json.loads(e.body) error_code = response_body.get('error_code') error_message = response_body.get('error_message') # Handle specific error codes or general errors ``` ### Exception Classes - **ApiException**: Standard API response error. - **ApiTypeError**: Type validation failure. - **ApiValueError**: Value validation failure. - **ApiAttributeError**: Attribute access error. - **ApiKeyError**: Dictionary key access error. - **NotFoundException**: 404 Not Found error. - **UnauthorizedException**: 401 Unauthorized error. - **ForbiddenException**: 403 Forbidden error. - **ServiceException**: 5xx Server errors. ``` -------------------------------- ### Custom SSL Certificate Configuration Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Example of configuring the Plaid client to use a custom SSL certificate for secure connections. Ensure `verify_ssl` is set to `True` when providing a custom CA bundle. ```python configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={...}, ssl_ca_cert='/path/to/ca-bundle.crt', ) configuration.verify_ssl = True ``` -------------------------------- ### Nested Model Structure Example Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Illustrates a transaction object containing nested dictionary structures for 'location' and 'balances', showing how complex data is organized. ```python # Transaction with nested location transaction = { 'transaction_id': '123', 'location': { # Nested object 'address': '123 Main St', 'city': 'Springfield', 'region': 'IL', }, 'balances': { # Nested object 'current': 1000.50, 'available': 950.25, }, } ``` -------------------------------- ### Create datetime object with timezone Source: https://github.com/plaid/plaid-python/blob/master/README.md Use `datetime.datetime` with timezone information for fields specifying `format: date-time`. The example includes `datetime.timezone.utc`. ```python from datetime import datetime a = datetime(2022, 5, 5, 22, 35, 49, tzinfo=datetime.timezone.utc) ``` -------------------------------- ### Basic Plaid API Exception Handling Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/errors.md A fundamental pattern for catching generic Plaid API exceptions (ApiException). This example shows how to parse the error body to extract the error code and message. ```python import plaid import json try: request = AccountsGetRequest(access_token=access_token) response = client.accounts_get(request) except plaid.ApiException as e: error_data = json.loads(e.body) print(f"Error: {error_data['error_code']} - {error_data['error_message']}") ``` -------------------------------- ### Create date object Source: https://github.com/plaid/plaid-python/blob/master/README.md Use `datetime.date` to represent dates when the API reference specifies `format: date`. This example shows creating a date object directly and from an ISO format string. ```python from datetime import date a = date(2022, 5, 5) b = date.fromisoformat('2022-05-05') ``` -------------------------------- ### Get Employment Verification Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieves employment verification details for a given item using an access token. Use this to get employer name and employment status. ```python from plaid.model.employment_verification_get_request import EmploymentVerificationGetRequest request = EmploymentVerificationGetRequest(access_token=access_token) response = client.employment_verification_get(request) for employment in response['employment']: print(f"Employer: {employment['employer']['name']}") print(f"Status: {employment['employment_status']}") ``` -------------------------------- ### Plaid Python Configuration Constructor Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Illustrates the parameters available when initializing the Configuration class. This includes setting the host, API keys, and various other options for SDK behavior. ```python Configuration( host: str = None, api_key: dict = None, api_key_prefix: dict = None, access_token: str = None, username: str = None, password: str = None, discard_unknown_keys: bool = False, disabled_client_side_validations: str = "", server_index: int = None, server_variables: dict = None, server_operation_index: dict = None, server_operation_variables: dict = None, ssl_ca_cert: str = None, ) ``` -------------------------------- ### Retrieve Asset Report as PDF Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Get an asset report in PDF format using the asset report token. The response is returned as bytes, which can then be written to a file. ```python from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest pdf_request = AssetReportPDFGetRequest(asset_report_token=asset_report_token) pdf = client.asset_report_pdf_get(pdf_request) with open('asset_report.pdf', 'wb') as f: f.write(pdf.read()) ``` -------------------------------- ### Initialize Configuration with Environment Variables Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Set up the Plaid configuration using environment variables for host, client ID, and secret. This is a common practice for managing sensitive credentials. ```python import os configuration = plaid.Configuration( host=os.environ.get('PLAID_ENV', plaid.Environment.Sandbox), api_key={ 'clientId': os.environ['PLAID_CLIENT_ID'], 'secret': os.environ['PLAID_SECRET'], } ) ``` -------------------------------- ### Get Real-Time Balance Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md Retrieves the real-time balance for an account. ```APIDOC ## GET /accounts/balance/get ### Description Retrieves the real-time balance for an account. ### Method GET ### Endpoint `/accounts/balance/get` ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token associated with the Item data is being requested for. ``` -------------------------------- ### Get Account Information Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md Retrieves detailed information about a specific account. ```APIDOC ## GET /accounts/get ### Description Retrieves detailed information about a specific account. ### Method GET ### Endpoint `/accounts/get` ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token associated with the Item data is being requested for. ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Shows how to set up the Configuration object for the Production environment. This requires your production client ID and secret. ```python configuration = plaid.Configuration( host=plaid.Environment.Production, api_key={ 'clientId': 'your_client_id', 'secret': 'your_secret', } ) ``` -------------------------------- ### Get Beacon User Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves details for an existing Beacon user using their user ID. ```python client.beacon_user_get( beacon_user_get_request: BeaconUserGetRequest, **kwargs ) -> BeaconUserGetResponse ``` -------------------------------- ### Create Business Verification Instance Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Initiate a business verification process. Optionally provide a webhook URL and user information. ```python client.business_verification_create(business_verification_create_request=BusinessVerificationCreateRequest(business_name=business_name, webhook_url=webhook_url, user=user)) ``` -------------------------------- ### Verification Endpoints Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/README.md This section covers the verification API endpoints provided by the Plaid Python SDK, including those for Identity, Employment, Income, Payroll, Bank Income, and Business Verification. Each endpoint is documented with its signature, parameters, return type, and usage examples. ```APIDOC ## Verification Endpoints ### Description Documentation for Plaid API endpoints related to verification, including Identity, Employment, Income, Payroll, Bank Income, and Business Verification. ### Endpoint Details Each endpoint includes: signature, parameters table, return type, throws clause, and usage example. ### Example Endpoint Documentation Structure: ```markdown ## POST /identity/verification/create ### Description Creates an Identity Verification attempt. ### Method POST ### Endpoint /identity/verification/create ### Parameters #### Request Body - **client_user_id** (string) - Required - A unique ID for the end-user - **template_id** (string) - Required - The ID of the Identity Verification template - **options** (object) - Optional - Options for the verification attempt ### Request Example ```json { "client_user_id": "user-123", "template_id": "tmpl_abc123" } ``` ### Response #### Success Response (200) - **identity_verification_id** (string) - The ID of the Identity Verification attempt - **request_id** (string) - A unique identifier for the request #### Response Example ```json { "identity_verification_id": "iv-sandbox-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" } ``` ``` ``` -------------------------------- ### Create Plaid Model from Dictionary Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Shows how to instantiate a Plaid SDK model, such as an Account object, by providing a dictionary representation of its data. ```python from plaid.model.account import Account account_dict = { 'account_id': 'acc_123', 'name': 'My Checking', 'type': 'checking', } account = Account.from_dict(account_dict) ``` -------------------------------- ### Get Identity Verification Details Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve the details and status of an existing identity verification by its ID. ```python from plaid.model.identity_verification_get_request import IdentityVerificationGetRequest request = IdentityVerificationGetRequest( identity_verification_id='id_verification_123', ) response = client.identity_verification_get(request) print(f"Status: {response['status']}") print(f"Verified: {response['verified_at']}") ``` -------------------------------- ### Request Options for AccountsGet Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Demonstrates how to use the `AccountsGetRequestOptions` to specify a list of account IDs when fetching account details. ```python from plaid.model.accounts_get_request import AccountsGetRequest from plaid.model.accounts_get_request_options import AccountsGetRequestOptions options = AccountsGetRequestOptions( accounts=['account_id_1', 'account_id_2'] ) request = AccountsGetRequest( access_token=access_token, options=options ) response = client.accounts_get(request) ``` -------------------------------- ### Handle Errors (Pre-8.0.0) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of handling ItemError and APIError using the older error handling mechanism. ```python try: client.Auth.get(access_token) except ItemError as e: if e.code == 'ITEM_LOGIN_REQUIRED': else: ... except APIError as e: if e.code == 'PLANNED_MAINTENANCE': # inform user else: ... ``` -------------------------------- ### AccountsGetRequest with Options Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Demonstrates how to use the `AccountsGetRequestOptions` to specify a list of account IDs when fetching account information. ```APIDOC ## AccountsGetRequest with Options ### Description This example shows how to filter the accounts for which to retrieve balance information by providing a list of `account_id`s in the `options` parameter of the `AccountsGetRequest`. ### Method POST ### Endpoint `/accounts/get` ### Parameters #### Request Body - **access_token** (string) - Required - The access token associated with the Item data is being requested for. - **options** (AccountsGetRequestOptions) - Optional - An object containing optional parameters. - **accounts** (list of strings) - Optional - Filter results to return only the specified accounts. ``` -------------------------------- ### Get CRA Check Lending Score Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves the lending score from a CRA check. Requires a user token. ```python client.cra_check_report_lend_score_get( cra_check_report_lend_score_get_request: CraCheckReportLendScoreGetRequest, **kwargs ) -> CraCheckReportLendScoreGetResponse ``` -------------------------------- ### Manage Default Configuration Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Demonstrates how to retrieve, modify, and set the default configuration for the Plaid client. This allows for consistent settings across multiple client instances. ```python # Get default configuration default_config = plaid.Configuration.get_default_copy() # Modify it default_config.host = plaid.Environment.Sandbox default_config.api_key = { 'clientId': 'your_client_id', 'secret': 'your_secret', } # Set as default for new clients plaid.Configuration.set_default(default_config) ``` -------------------------------- ### Get CRA Check Income Insights Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves income insights from a CRA check. Requires a user token. ```python client.cra_check_report_income_insights_get( cra_check_report_income_insights_get_request: CraCheckReportIncomeInsightsGetRequest, **kwargs ) -> CraCheckReportIncomeInsightsGetResponse ``` -------------------------------- ### Get CRA Check Cashflow Insights Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves cashflow insights from a CRA check. Requires a user token. ```python client.cra_check_report_cashflow_insights_get( cra_check_report_cashflow_insights_get_request: CraCheckReportCashflowInsightsGetRequest, **kwargs ) -> CraCheckReportCashflowInsightsGetResponse ``` -------------------------------- ### ApiClient Constructor Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Shows the parameters for initializing the ApiClient, which requires a Configuration object and allows for additional runtime settings like custom headers. ```python ApiClient( configuration: Configuration = None, header_name: str = None, header_value: str = None, cookie: str = None, pool_threads: int = 1, ) ``` -------------------------------- ### Create Income Verification Instance Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Creates an income verification instance with a client user ID and specified products. A webhook URL can be provided for notifications. ```python from plaid.model.income_verification_create_request import IncomeVerificationCreateRequest request = IncomeVerificationCreateRequest( client_user_id='user_123', products=['income_verification'], ) response = client.income_verification_create(request) link_token = response['link_token'] ``` -------------------------------- ### Get Cashflow Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves a cashflow report for a given user token. The response includes cashflow insights. ```python from plaid.model.cashflow_report_get_request import CashflowReportGetRequest request = CashflowReportGetRequest(user_token=user_token) response = client.cashflow_report_get(request) print(f"Cashflow metrics: {response['cashflow_insights']}") ``` -------------------------------- ### Using date for Date Fields Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Demonstrates how to use `datetime.date` objects for fields formatted as dates. Supports direct instantiation or creation from an ISO format string. ```python from datetime import date start_date = date(2022, 5, 5) # or start_date = date.fromisoformat('2022-05-05') request = TransactionsGetRequest( access_token=access_token, start_date=start_date, end_date=date(2023, 1, 1), ) ``` -------------------------------- ### Get Item Information Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieves details about a specific item. Useful for checking item status or associated data. ```python from plaid.model.item_get_request import ItemGetRequest request = ItemGetRequest(access_token=access_token) response = client.item_get(request) print(f"Item ID: {response['item']['item_id']}") print(f"Institution: {response['item']['institution_id']}") print(f"Status: {response['item']['error']}") ``` -------------------------------- ### Configure SDK and Plaid Logging Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/configuration.md Set up Python's standard logging module to capture debug information from the Plaid SDK and underlying HTTP libraries. This is essential for troubleshooting. ```python import logging # Configure SDK logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Enable Plaid debug logging plaid_logger = logging.getLogger('plaid') plaid_logger.setLevel(logging.DEBUG) # Enable urllib3 debug logging (HTTP requests) urllib3_logger = logging.getLogger('urllib3') urllib3_logger.setLevel(logging.DEBUG) ``` -------------------------------- ### Get Bank Income Data Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve bank income data that has been verified from statements. Requires a user token. ```python from plaid.model.credit_bank_income_get_request import CreditBankIncomeGetRequest request = CreditBankIncomeGetRequest(user_token=user_token) response = client.credit_bank_income_get(request) for summary in response['income_summaries']: print(f"Income: {summary['total_income']}") print(f"Confidence: {summary['confidence']}") ``` -------------------------------- ### Plaid Configuration Object Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Instantiate the Configuration object for the Plaid SDK. Common parameters include host, API keys, and SSL certificate paths. ```python config = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': 'client_id_string', 'secret': 'secret_string', } ) ``` -------------------------------- ### Get Payroll Income Data Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve payroll income data for a user. Requires a user token from verification. ```python from plaid.model.credit_payroll_income_get_request import CreditPayrollIncomeGetRequest request = CreditPayrollIncomeGetRequest(user_token=user_token) response = client.credit_payroll_income_get(request) for income in response['payroll_income']: print(f"Employer: {income['employer']['name']}") print(f"Annual income: {income['annual_income']}") ``` -------------------------------- ### Instantiate PlaidApi Client Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Create an instance of the PlaidApi client using an initialized ApiClient. This client object is used to interact with all Plaid API endpoints. ```python from plaid.api import plaid_api client = plaid_api.PlaidApi(api_client) response = client.accounts_balance_get(request) ``` -------------------------------- ### CountryCode Enum Values Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Provides examples of supported country codes for Plaid services, noting that over 40 countries are supported. ```python CountryCode('US') CountryCode('GB') CountryCode('CA') CountryCode('DE') CountryCode('FR') CountryCode('NL') CountryCode('ES') CountryCode('IE') CountryCode('IT') # ... 40+ countries supported ``` -------------------------------- ### File Upload for Asset Report PDF Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Demonstrates how to request an asset report PDF and save the response to a file. This involves creating a request object and then writing the binary response content to a local file. ```python from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest pdf_request = AssetReportPDFGetRequest(asset_report_token=token) pdf_response = client.asset_report_pdf_get(pdf_request) # Save PDF with open('asset_report.pdf', 'wb') as f: f.write(pdf_response.read()) ``` -------------------------------- ### Plaid Python SDK File Structure Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/README.md Overview of the directory structure for the Plaid Python SDK documentation. This helps in locating specific documentation files. ```text output/ ├── README.md ← You are here ├── INDEX.md ← Start here for complete guide ├── plaid-python-api-reference.md ← Overview & quick start ├── configuration.md ← Configuration reference ├── errors.md ← Error handling ├── types.md ← Data types & models └── api-reference/ ├── endpoints-core.md ← 20 core endpoints ├── endpoints-verification.md ← 18 verification endpoints └── endpoints-reports.md ← 20 report endpoints ``` -------------------------------- ### Get Investment Transactions Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve investment transactions for a specified date range. Requires an access token and start/end dates. ```python client.investments_transactions_get( investments_transactions_get_request: InvestmentsTransactionsGetRequest, **kwargs ) -> InvestmentsTransactionsGetResponse ``` -------------------------------- ### Initialize Plaid API Client Source: https://github.com/plaid/plaid-python/blob/master/README.md Create a PlaidApi object to interact with Plaid API endpoints. Ensure you replace 'client_id' and 'secret' with your actual credentials. The environment can be set to 'Production' or 'Sandbox'. ```python import plaid from plaid.api import plaid_api # Available environments are # 'Production' # 'Sandbox' configuration = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': client_id, 'secret': secret, } ) api_client = plaid.ApiClient(configuration) client = plaid_api.PlaidApi(api_client) ``` -------------------------------- ### Get Investment Holdings Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve investment holdings for a given item. This requires an access token and can be filtered with optional parameters. ```python from plaid.model.investments_holdings_get_request import InvestmentsHoldingsGetRequest request = InvestmentsHoldingsGetRequest( access_token=access_token, ) response = client.investments_holdings_get(request) for holding in response['holdings']: security = next(s for s in response['securities'] if s['security_id'] == holding['security_id']) print(f"{security['name']}: {holding['quantity']} units @ ${holding['institution_price']}") ``` -------------------------------- ### Create Asset Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Use this endpoint to create a new asset report. You must provide a list of client item IDs and the number of days of history to include. The response contains a token to retrieve the report. ```python from plaid.model.asset_report_create_request import AssetReportCreateRequest request = AssetReportCreateRequest( client_ids=['item_id_1', 'item_id_2'], days_requested=90, ) response = client.asset_report_create(request) asset_report_token = response['asset_report_token'] ``` -------------------------------- ### Get Cashflow Report Transactions Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves the transaction data that underlies a cashflow report, using the provided user token. ```python client.cashflow_report_transactions_get( cashflow_report_transactions_get_request: CashflowReportTransactionsGetRequest, **kwargs ) -> CashflowReportTransactionsGetResponse ``` -------------------------------- ### Run Docker Container with Credentials Source: https://github.com/plaid/plaid-python/blob/master/CONTRIBUTING.md Runs the Docker container for client tests, injecting Plaid API credentials as environment variables. Obtain your client_id and sandbox secret from the Plaid Dashboard. ```bash docker run --rm -e CLIENT_ID=$CLIENT_ID -e SECRET=$SECRET plaid-python ``` -------------------------------- ### Create Beacon Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Use this endpoint to create a Beacon report. It requires a user ID and a fraud confirmation status. ```python client.beacon_report_create( beacon_report_create_request: BeaconReportCreateRequest, **kwargs ) -> BeaconReportCreateResponse ``` -------------------------------- ### Get Bank Income PDF Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve a PDF document of verified bank income. Requires a user token. ```python from plaid.model.credit_bank_income_pdf_get_request import CreditBankIncomePDFGetRequest request = CreditBankIncomePDFGetRequest(user_token=user_token) pdf_bytes = client.credit_bank_income_pdf_get(request) with open('income_report.pdf', 'wb') as f: f.write(pdf_bytes.read()) ``` -------------------------------- ### Enum Data Types (8.0.0+) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of representing products and country codes using Python classes from version 8.0.0 onwards. ```python products=[Products('auth'), Products('transactions')], country_codes=[CountryCode('US')], ``` -------------------------------- ### business_verification_create Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Initiates a business verification process. This endpoint creates a new verification instance and can optionally include a webhook URL and user information. ```APIDOC ## business_verification_create ### Description Create a business verification instance. ### Method POST ### Endpoint /business_verification/create ### Parameters #### Request Body - **business_name** (str) - Required - Name of the business. - **webhook_url** (str) - Optional - Webhook URL for completion notifications. - **user** (IdentityVerificationUser) - Optional - User information for the verification. ### Request Example ```json { "business_name": "Example Business Inc.", "webhook_url": "https://example.com/webhook", "user": { "email": "user@example.com" } } ``` ### Response #### Success Response (200) - **link_token** (str) - The token to initiate the verification flow. - **expires_at** (str) - The expiration date of the link token. #### Response Example ```json { "link_token": "link-sandbox-...", "expires_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Cursor-Based Pagination for TransactionsSync Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Illustrates how to paginate through transactions using cursor-based iteration for sync endpoints. It continuously fetches transactions until `has_more` is false. ```python from plaid.model.transactions_sync_request import TransactionsSyncRequest request = TransactionsSyncRequest( access_token=access_token, ) response = client.transactions_sync(request) transactions = response['added'] while response['has_more']: request = TransactionsSyncRequest( access_token=access_token, cursor=response['next_cursor'] ) response = client.transactions_sync(request) transactions += response['added'] ``` -------------------------------- ### Get Auth Data Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve authentication data, including account numbers and routing information, for an item. Requires an access token. ```python from plaid.model.auth_get_request import AuthGetRequest request = AuthGetRequest( access_token=access_token, ) response = client.auth_get(request) for account in response['accounts']: print(f"Account: {account['account_id']}") print(f" Routing: {account['routing_number']}") print(f" Account #: {account['account_number']}") ``` -------------------------------- ### Get Identity Information for an Item Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Retrieve names, addresses, emails, and phone numbers associated with an item using its access token. ```python from plaid.model.identity_get_request import IdentityGetRequest request = IdentityGetRequest(access_token=access_token) response = client.identity_get(request) for account in response['accounts']: for owner in account['owners']: print(f"Owner: {owner['names']}") for addr in owner['addresses']: print(f" Address: {addr['street']}, {addr['city']}, {addr['region']}") ``` -------------------------------- ### income_verification_create Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-verification.md Initiates an income verification process, returning a link token for user redirection. ```APIDOC ## income_verification_create ### Description Create an income verification instance. ### Method POST ### Endpoint /income/verification/create ### Parameters #### Request Body - **client_user_id** (str) - Required - End user's ID in your system - **products** (list) - Required - List of verification products - **webhook_url** (str) - Optional - Webhook URL for completion notifications - **user** (object) - Optional - User information ### Request Example ```json { "client_user_id": "user_123", "products": ["income_verification"] } ``` ### Response #### Success Response (200) - **link_token** (str) - The link token to be used to initialize Plaid Link. - **id** (str) - The ID of the income verification instance. #### Response Example ```json { "link_token": "link_token_...", "id": "income_verification_id_..." } ``` ``` -------------------------------- ### Handling ApiValueError Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/errors.md Catch ApiValueError when a parameter value is invalid or out of range. This example demonstrates handling an invalid count value for the institutions_get request. ```python try: from plaid.model.institutions_get_request import InstitutionsGetRequest # count must be 1-500 request = InstitutionsGetRequest( count=1000, # Invalid: exceeds maximum offset=0, ) response = client.institutions_get(request) except plaid.ApiValueError as e: print(f"Value error: {e}") ``` -------------------------------- ### Handling ApiTypeError Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/errors.md Catch ApiTypeError when a request parameter has the wrong type. This example shows how to access details about the expected types and the location of the error. ```python try: # date parameter expects datetime.date, not string request = TransactionsGetRequest( access_token=access_token, start_date='2022-01-01', # Wrong: should be date object end_date='2023-01-01', ) response = client.transactions_get(request) except plaid.ApiTypeError as e: print(f"Type error: {e}") print(f"Location: {e.path_to_item}") print(f"Expected: {e.valid_classes}") ``` -------------------------------- ### Handle Errors (8.0.0+) Source: https://github.com/plaid/plaid-python/blob/master/README.md Example of handling Plaid API exceptions using the new error handling mechanism from version 8.0.0 onwards. ```python try: request = AssetReportGetRequest( asset_report_token=asset_report_token, ) return client.asset_report_get(request) except plaid.ApiException as e: response = json.loads(e.body) if response['error_code'] == 'ITEM_LOGIN_REQUIRED': else: ``` -------------------------------- ### Configuration Class Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Manages SDK configuration including API credentials and connection settings. It allows customization of API host, keys, SSL certificates, and other connection parameters. ```APIDOC ## Configuration **File**: `plaid/configuration.py` Manages SDK configuration including API credentials and connection settings. ```python Configuration( host: str = None, api_key: dict = None, api_key_prefix: dict = None, access_token: str = None, username: str = None, password: str = None, discard_unknown_keys: bool = False, disabled_client_side_validations: str = "", server_index: int = None, server_variables: dict = None, server_operation_index: dict = None, server_operation_variables: dict = None, ssl_ca_cert: str = None, ) -> Configuration ``` **Common Parameters**: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | host | str | `https://production.plaid.com` | Base URL for API requests | | api_key | dict | None | Dictionary with `clientId` and `secret` keys | | ssl_ca_cert | str | None | Path to CA certificate file for SSL verification | | verify_ssl | bool | True | Whether to verify SSL certificates | | discard_unknown_keys | bool | False | Ignore unknown properties in API responses | | disabled_client_side_validations | str | "" | Comma-separated JSON schema validation keywords to disable | **Example**: ```python config = plaid.Configuration( host=plaid.Environment.Sandbox, api_key={ 'clientId': 'client_id_string', 'secret': 'secret_string', } ) ``` ``` -------------------------------- ### Import Options Models Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Import model classes for optional request parameters. These follow the pattern RequestOptions. ```python from plaid.model.accounts_get_request_options import AccountsGetRequestOptions from plaid.model.transactions_get_request_options import TransactionsGetRequestOptions from plaid.model.bank_transfer_create_request_options import BankTransferCreateRequestOptions ``` -------------------------------- ### Get Institutions Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve a list of institutions with optional filtering by country codes and pagination. Use this to display available financial institutions to users. ```python from plaid.model.institutions_get_request import InstitutionsGetRequest from plaid.model.country_code import CountryCode request = InstitutionsGetRequest( count=50, offset=0, country_codes=[CountryCode('US')], ) response = client.institutions_get(request) for institution in response['institutions']: print(f"{institution['name']} - ID: {institution['institution_id']}") ``` -------------------------------- ### Get Cashflow Report Insights Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Fetches the specific cashflow insights associated with a user token. The response contains detailed insights data. ```python client.cashflow_report_insights_get( cashflow_report_insights_get_request: CashflowReportInsightsGetRequest, **kwargs ) -> CashflowReportInsightsGetResponse ``` -------------------------------- ### Configuring Thread Pool for Async Requests Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Demonstrates how to configure the thread pool size for asynchronous requests when initializing `ApiClient`. Alternatively, a context manager can be used for automatic resource cleanup. ```python api_client = plaid.ApiClient(configuration, pool_threads=10) ``` ```python with plaid.ApiClient(configuration) as api_client: client = plaid_api.PlaidApi(api_client) response = client.accounts_balance_get(request, async_req=True) result = response.get() ``` -------------------------------- ### Using Enums for Products and Country Codes Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/plaid-python-api-reference.md Illustrates how to use enum-like classes for string enums like `Products` and `CountryCode`. These are used when creating requests that require specific enumerated values. ```python from plaid.model.products import Products from plaid.model.country_code import CountryCode request = LinkTokenCreateRequest( user=LinkTokenUser(...), client_name='My App', products=[Products('auth'), Products('transactions')], country_codes=[CountryCode('US')], ) ``` -------------------------------- ### Create Link Token Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md Creates a link token, which is used to initialize Plaid Link for the user. ```APIDOC ## Create Link Token ### Description Creates a link token, which is used to initialize Plaid Link for the user. ### Method POST ### Endpoint `/link/token/create` ### Parameters #### Request Body - **user** (object) - Required - Information about the user. - **client_user_id** (string) - Required - A unique identifier for the end user. - **client_name** (string) - Required - The name of your application. - **products** (array) - Required - An array of Plaid products to use for the link_token. ### Request Example ```python { "user": { "client_user_id": "user_123" }, "client_name": "My App", "products": ["auth", "transactions"] } ``` ### Response #### Success Response (200) - **link_token** (string) - The link token. - **expiration** (string) - The expiration date of the link token. - **request_id** (string) - A unique identifier for the request, used for troubleshooting. #### Response Example ```json { "link_token": "link-sandbox-1234567890abcdef", "expiration": "2023-11-26T23:59:59Z", "request_id": "abcdef123456" } ``` ``` -------------------------------- ### Get Beacon Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieve details for a specific Beacon report using its ID. This is useful for checking the status and results of a previously created report. ```python client.beacon_report_get( beacon_report_get_request: BeaconReportGetRequest, **kwargs ) -> BeaconReportGetResponse ``` -------------------------------- ### Get CRA Check Base Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-reports.md Retrieves the base report details from a CRA check, including account summaries. Requires the user token. ```python client.cra_check_report_base_report_get( cra_check_report_base_report_get_request: CraCheckReportBaseReportGetRequest, **kwargs ) -> CraCheckReportBaseReportGetResponse ``` -------------------------------- ### Create Link Token for Plaid Link Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md Generate a `link_token` required to initialize Plaid Link. This token is used on the client-side to initiate the account linking flow. ```python from plaid.model.link_token_create_request import LinkTokenCreateRequest from plaid.model.link_token_user import LinkTokenUser user = LinkTokenUser(client_user_id='user_123') request = LinkTokenCreateRequest( user=user, client_name='My App', products=['auth', 'transactions'], ) response = client.link_token_create(request) link_token = response['link_token'] ``` -------------------------------- ### LinkTokenCreateRequestOptions Structure Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Details key parameters for creating a Link token, including user information, client name, product selection, country codes, language, account filters, and webhook configuration. ```python { 'user': LinkTokenUser, 'client_name': str, 'products': list[str] | None, # [Products] enum values 'country_codes': list[str] | None, # [CountryCode] enum values 'language': str | None, # e.g., 'en', 'es', 'fr' 'account_filters': dict | None, # Filter by account types 'webhook': str | None, 'link_customization_name': str | None, 'redirect_uri': str | None, # For Link flow redirect 'android_package_name': str | None, # For mobile apps } ``` -------------------------------- ### Create Asset Report Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/INDEX.md Generate an asset report for one or more items. Specify the number of `days_requested` for the report. ```python from plaid.model.asset_report_create_request import AssetReportCreateRequest request = AssetReportCreateRequest( client_ids=['item_1', 'item_2'], days_requested=90, ) response = client.asset_report_create(request) asset_report_token = response['asset_report_token'] ``` -------------------------------- ### Products Enum Values Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/types.md Lists the available Plaid products that can be requested, such as 'auth', 'transactions', and 'investments'. ```python Products('auth') Products('transactions') Products('income_verification') Products('asset_report') Products('investments') Products('liabilities') Products('payment_initiation') Products('bank_transfer') Products('identity') Products('beacon') ``` -------------------------------- ### Handling ApiKeyError Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/errors.md Catch ApiKeyError when trying to access a missing key in a response dictionary. This example illustrates how to handle missing keys when parsing API results. ```python try: response = client.accounts_get(request) # Accessing missing key value = response['non_existent_key'] except plaid.ApiKeyError as e: print(f"Key error: {e}") ``` -------------------------------- ### Get Institution by ID Source: https://github.com/plaid/plaid-python/blob/master/_autodocs/api-reference/endpoints-core.md Retrieve details for a specific financial institution using its unique ID. Useful for displaying specific institution information after a user selection. ```python from plaid.model.institutions_get_by_id_request import InstitutionsGetByIdRequest request = InstitutionsGetByIdRequest( institution_id='ins_12345', ) response = client.institutions_get_by_id(request) print(f"Institution: {response['institution']['name']}") ``` -------------------------------- ### Retrieve Asset Report PDF Source: https://github.com/plaid/plaid-python/blob/master/README.md Fetch an asset report in PDF format using the `asset_report_token`. The retrieved PDF content is then written to a local file named `asset_report.pdf`. ```python from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest pdf_request = AssetReportPDFGetRequest(asset_report_token=PDF_TOKEN) pdf = client.asset_report_pdf_get(pdf_request) FILE = open('asset_report.pdf', 'wb') FILE.write(pdf.read()) FILE.close() ```