Skip to content

Fix optional translation fields in websocket Error model#226

Merged
GrandMoff100 merged 1 commit intodevfrom
copilot/fix-error-responses-bug
Mar 1, 2026
Merged

Fix optional translation fields in websocket Error model#226
GrandMoff100 merged 1 commit intodevfrom
copilot/fix-error-responses-bug

Conversation

Copy link
Contributor

Copilot AI commented Mar 1, 2026

Home Assistant's websocket API doesn't always include translation_key, translation_placeholders, and translation_domain in error responses, but the Error Pydantic model required them — causing a ValidationError on valid server responses like invalid_format errors.

Changes

  • homeassistant_api/models/websocket.py: Made translation_key, translation_placeholders, and translation_domain optional (None default) on the Error model
  • tests/test_errors.py: Added test_error_model_without_optional_fields to assert Error parses correctly with only code and message
# Before — raises ValidationError when translation fields are absent
class Error(BaseModel):
    code: str
    message: str
    translation_key: str
    translation_placeholders: dict[str, str]
    translation_domain: str

# After
class Error(BaseModel):
    code: str
    message: str
    translation_key: Optional[str] = None
    translation_placeholders: Optional[dict[str, str]] = None
    translation_domain: Optional[str] = None
Original prompt

This section details on the original issue you should resolve

<issue_title>[Library Bug] error responses do not always contain error.translation_key and related keys.</issue_title>
<issue_description>Describe the bug
Websocket API error responses do not always contain error.translation_key and related keys.

To Reproduce

from homeassistant_api import WebsocketClient

with WebsocketClient(
    'wss://<domain>/api/websocket',
    '<long lived token>'
) as ws_client:
    res_id = ws_client.send("recorder/statistics_during_period",
        start_time="2025-12-30T17:20:00.000Z",
        end_time="2025-12-30T22:20:00.000Z",
        #statistic_ids=["sensor.display_switch_electric_consumption_kwh"],
        #period="hour" # this triggers the server side error because the fields are required.
    )
    resp = ws_client.recv(res_id)
    print(resp)

The server sends this back:

{'id': 2, 'type': 'result', 'success': False, 'error': {'code': 'invalid_format', 'message': "required key not provided @ data['period']. Got None\nrequired key not provided @ data['start_time']. Got None\nrequired key not provided @ data['statistic_ids']. Got None"}}

Resulting in the following output:

pydantic_core._pydantic_core.ValidationError: 3 validation errors for ErrorResponse
error.translation_key
  Field required [type=missing, input_value={'code': 'invalid_format'...tistic_ids']. Got None"}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.12/v/missing
error.translation_placeholders
  Field required [type=missing, input_value={'code': 'invalid_format'...tistic_ids']. Got None"}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.12/v/missing
error.translation_domain
  Field required [type=missing, input_value={'code': 'invalid_format'...tistic_ids']. Got None"}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.12/v/missing

Expected behavior
A clear and concise description of what you expected to happen.
The errors should be accepted without these keys since clearly they are optional for the server.

Desktop (please complete the following information):

  • OS: macOS
  • OS Version Sonoma 14.8.1
  • HomeAssistantAPI Version: 5.0.2.post2

Workaround

Patch the BaseError model to look like this:

class Error(BaseModel):
    code: str
    message: str
    translation_key: str | None = None
    translation_placeholders: dict[str, str] | None = None
    translation_domain: str | None = None

Proper solution will need some special pydantic magic I assume.
</issue_description>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI changed the title [WIP] Fix error responses to include translation keys Fix optional translation fields in websocket Error model Mar 1, 2026
…in optional in Error model

Co-authored-by: GrandMoff100 <51765903+GrandMoff100@users.noreply.github.com>
@codecov
Copy link

codecov bot commented Mar 1, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.46%. Comparing base (21fecd8) to head (41cc4b6).

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #226      +/-   ##
==========================================
+ Coverage   97.45%   97.46%   +0.01%     
==========================================
  Files          25       25              
  Lines        1648     1655       +7     
==========================================
+ Hits         1606     1613       +7     
  Misses         42       42              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@GrandMoff100 GrandMoff100 marked this pull request as ready for review March 1, 2026 06:49
@GrandMoff100 GrandMoff100 self-requested a review as a code owner March 1, 2026 06:49
@GrandMoff100 GrandMoff100 merged commit abf67f9 into dev Mar 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Library Bug] error responses do not always contain error.translation_key and related keys.

2 participants