plaid-python

repository·master·Indexed 19 days ago

https://github.com/plaid/plaid-python

The official Python client library for the Plaid API, generated from the Plaid OpenAPI specification. It enables developers to integrate Plaid's financial data services into Python 3 applications using the PlaidApi client, specific request models, and a Configuration and ApiClient pattern.

Tokens
2.2K
Snippets
9
Records
10
Agent score
18%

What's inside plaid-python

  1. Use dates and datetimes in requests

    master

    In this library, dates and datetimes are represented as Python datetime.date or datetime.datetime objects rather than strings.

    • For fields with format: date, use datetime.date or date.fromisoformat().
    • For fields with format: date-time, use datetime.datetime and must include time zone information (e.g., using timezone.utc). Failing to include time zone information will result in an error.

    You can convert strings to these objects using datetime.strptime().

    from datetime import date, datetime, timezone
    
    # format: date
    a = date(2022, 5, 5)
    b = date.fromisoformat('2022-05-05')
    
    # format: date-time (Time zone is required)
    c = datetime(2022, 5, 5, 22, 35, 49, tzinfo=timezone.utc)
  2. Migrate from pre-8.0.0 to latest

    master

    Significant changes occurred in version 8.0.0 (August 2021):

    1. Client Initialization: Moved from plaid.Client to a Configuration and ApiClient pattern.
    2. Endpoints: Requests now require specific request models (e.g., AuthGetRequest), and function names now include underscores (e.g., client.auth_get() instead of client.Auth.get()).
    3. Errors: Switched from specific error classes (like ItemError) to catching plaid.ApiException and parsing the JSON body for error_code.
    4. Enums: Enums are now Python classes with restricted values (e.g., Products('auth')) instead of raw strings.
    5. Configuration: Some options like timeouts moved from global client configuration to per-request arguments (e.g., _request_timeout=60).
  3. Initialize the PlaidApi client

    master

    To call Plaid endpoints, you must create a PlaidApi object. This involves configuring a plaid.Configuration object with your credentials and the target environment, then passing that configuration to a plaid.ApiClient, which is finally used to instantiate plaid_api.PlaidApi.

    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)
  4. Convert API responses to JSON

    master

    The library uses models (e.g., TransactionsSyncResponse) to encapsulate API responses. To convert a response object to a JSON string, use the .to_dict() method on the response object and then pass it to json.dumps().

    import json
    ...
    # response is an instance of a model like TransactionsSyncResponse
    response = ... 
    # to_dict makes it first a python dictionary, and then we turn it into a string JSON.
    json_string = json.dumps(response.to_dict(), default=str)
  5. Handle Plaid API errors

    master

    All non-200 HTTP responses will throw a plaid.ApiException. To determine the specific error type, you should parse the exception's body as JSON and check the error_code attribute. For example, if the error code is ITEM_LOGIN_REQUIRED, the user's login information has changed and you may need to generate a new public_token.

    import plaid
    import json
    from plaid.model.asset_report_get_request import AssetReportGetRequest
    
    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)
        # check the code attribute of the error to determine the specific error
        if response['error_code'] == 'ITEM_LOGIN_REQUIRED':
            # the users' login information has changed, generate a public_token
            # for the user and initialize Link in update mode to
            # restore access to this user's data
            pass
        else:
            ...
  6. Retrieve Transactions using TransactionsSync (preferred)

    master

    The transactions_sync method is the preferred way to retrieve transactions. Because results are paginated, you must use a while loop to check the has_more flag and provide the next_cursor in subsequent requests to retrieve all transactions.

    import plaid
    from plaid.model.transactions_sync_request import TransactionsSyncRequest
    
    request = TransactionsSyncRequest(
        access_token=access_token,
    )
    response = client.transactions_sync(request)
    transactions = response['added']
    
    # the transactions in the response are paginated, so make multiple calls while incrementing the cursor to
    # retrieve all transactions
    while (response['has_more']):
        request = TransactionsSyncRequest(
            access_token=access_token,
            cursor=response['next_cursor']
        )
        response = client.transactions_sync(request)
        transactions += response['added']
  7. Remove an Item

    master

    Use ItemRemoveRequest with an existing access_token to remove an Item from your integration.

    import plaid
    from plaid.model.item_remove_request import ItemRemoveRequest
    
    # Provide the access token for the Item you want to remove
    request = ItemRemoveRequest(
        access_token=accessToken
    )
    response = client.item_remove(request)
  8. Exchange a public_token for an access_token

    master

    Use ItemPublicTokenExchangeRequest to exchange a public_token received from Plaid Link for a permanent Plaid access token.

    import plaid
    from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
    
    # the public token is received from Plaid Link
    exchange_request = ItemPublicTokenExchangeRequest(
        public_token=pt_response['public_token']
    )
    exchange_response = client.item_public_token_exchange(exchange_request)
    access_token = exchange_response['access_token']
  9. Retrieve Asset Report PDF

    master

    Use AssetReportPDFGetRequest to retrieve an asset report in PDF format. The response can be read and written directly to a file.

    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()