From 00e6dafb7c1ff654a2917890f987069dcd82014e Mon Sep 17 00:00:00 2001 From: Sanjay Santhanam <51058514+Sanjays2402@users.noreply.github.com> Date: Thu, 23 Jul 2026 00:39:17 -0700 Subject: [PATCH] fix: normalize API error codes to strings Numeric API error codes currently contradict the public string annotation. Normalize non-null values and cover the runtime behavior with a regression test. --- src/openai/_exceptions.py | 3 ++- tests/test_client.py | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 86f44b0e15..721182d7e5 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -71,7 +71,8 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) self.body = body if is_dict(body): - self.code = cast(Any, construct_type(type_=Optional[str], value=body.get("code"))) + code = body.get("code") + self.code = str(code) if code is not None else None self.param = cast(Any, construct_type(type_=Optional[str], value=body.get("param"))) self.type = cast(Any, construct_type(type_=str, value=body.get("type"))) else: diff --git a/tests/test_client.py b/tests/test_client.py index bdbc2ce26b..febf157d73 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -125,6 +125,12 @@ def _get_open_connections(client: OpenAI | AsyncOpenAI) -> int: class TestOpenAI: + def test_api_error_code_is_string(self) -> None: + response = httpx.Response(400, request=httpx.Request("GET", base_url)) + error = APIStatusError("Error", response=response, body={"code": 404}) + + assert error.code == "404" + @pytest.mark.respx(base_url=base_url) def test_raw_response(self, respx_mock: MockRouter, client: OpenAI) -> None: respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"}))