Skip to content

Fix KeyError exceptions when API returns unexpected response formats #12

@house2001

Description

@house2001

Problem

The library throws KeyError exceptions when the ChargePoint API returns responses in unexpected formats. This causes integrations (like Home Assistant) to fail completely
rather than handling the errors gracefully.

Specific Errors:

  1. KeyError: 'get_pandas' in get_home_chargers() at line 264
  2. KeyError: 'get_panda_status' in get_home_charger_status() at line 320

Error Details

File "/usr/local/lib/python3.13/site-packages/python_chargepoint/client.py", line 264, in get_home_chargers
pandas = response.json()["get_pandas"]["device_ids"]
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
KeyError: 'get_pandas'

Root Cause

The code assumes the API will always return responses in the expected format:

  • get_home_chargers() expects: {"get_pandas": {"device_ids": [...]}}
  • get_home_charger_status() expects: {"get_panda_status": {...}}

However, the API may return different formats under certain conditions (authentication errors, empty results, API errors, etc.).

Solution

Add defensive error handling to gracefully handle unexpected response formats:

  • Check if expected fields exist before accessing them
  • Handle API error responses appropriately
  • Return sensible defaults (empty lists) when the response format is unexpected
  • Raise meaningful exceptions for actual errors

Testing

The expected API format still works correctly when tested directly, but fails in production environments, suggesting the API returns different response formats under
certain conditions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions