From 7c573aad76fbfbb8e625af091aba28ff63659629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20V=C3=A4lim=C3=A4ki?= Date: Wed, 18 Nov 2026 14:54:43 +0200 Subject: [PATCH 1/2] feat(client): add User-Agent --- CHANGELOG.md | 4 +++ generator/templates/client.py.jinja | 37 +++++++++++++++++---- tests/test_sdk_smoke.py | 46 ++++++++++++++++++++++++++ upcloud_api/client.py | 50 ++++++++++++++++++++++------- 4 files changed, 119 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 132e609..9404705 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Send `User-Agent: upcloud-python-api/`. A `User-Agent` value in `headers` is appended to it. + ## [3.0.0a1] - 2026-10-14 ### Changed diff --git a/generator/templates/client.py.jinja b/generator/templates/client.py.jinja index e886f34..adfcc26 100644 --- a/generator/templates/client.py.jinja +++ b/generator/templates/client.py.jinja @@ -1,9 +1,33 @@ +import importlib.metadata import ssl +from collections.abc import Mapping from typing import Any from attrs import define, field, evolve import httpx +try: + USER_AGENT = f"upcloud-python-api/{importlib.metadata.version('upcloud-api')}" +except importlib.metadata.PackageNotFoundError: + USER_AGENT = "upcloud-python-api/unknown" + + +def _apply_headers(current: httpx.Headers, headers: Mapping[str, str]) -> httpx.Headers: + """Copy current headers and apply new ones. A User-Agent value is appended to the current one""" + merged = httpx.Headers(current) + for name, value in headers.items(): + if name.lower() != "user-agent": + merged[name] = value + elif caller := value.strip(" \t"): + base = merged.get("User-Agent") + merged["User-Agent"] = f"{base} {caller}" if base else caller + return merged + + +def _request_headers(headers: Mapping[str, str]) -> httpx.Headers: + """Build request headers on top of the SDK User-Agent""" + return _apply_headers(httpx.Headers({"User-Agent": USER_AGENT}), headers) + {% set attrs_info = { "raise_on_unexpected_status": namespace( @@ -41,7 +65,7 @@ class Client: ``cookies``: A dictionary of cookies to be sent with every request - ``headers``: A dictionary of headers to be sent with every request + ``headers``: A dictionary of headers to be sent with every request. A ``User-Agent`` value is appended to the SDK default. ``timeout``: The maximum amount of a time a request can take. API functions will raise httpx.TimeoutException if this is exceeded. @@ -75,11 +99,12 @@ class Client: {% macro builders(self) %} def with_headers(self, headers: dict[str, str]) -> "{{ self }}": """Get a new client matching this one with additional headers""" + evolved = _apply_headers(httpx.Headers(self._headers), headers) if self._client is not None: - self._client.headers.update(headers) + self._client.headers = _apply_headers(self._client.headers, headers) if self._async_client is not None: - self._async_client.headers.update(headers) - return evolve(self, headers={**self._headers, **headers}) + self._async_client.headers = _apply_headers(self._async_client.headers, headers) + return evolve(self, headers=dict(evolved)) def with_cookies(self, cookies: dict[str, str]) -> "{{ self }}": """Get a new client matching this one with additional cookies""" @@ -115,7 +140,7 @@ class Client: self._client = httpx.Client( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, @@ -149,7 +174,7 @@ class Client: self._async_client = httpx.AsyncClient( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, diff --git a/tests/test_sdk_smoke.py b/tests/test_sdk_smoke.py index 36f55f1..82cc39a 100644 --- a/tests/test_sdk_smoke.py +++ b/tests/test_sdk_smoke.py @@ -171,6 +171,52 @@ def test_custom_token_prefix_and_header(self): self.assertEqual(http_client.headers["X-Custom"], "preserved") self.assertNotIn("Authorization", http_client.headers) + def test_user_agent_default_and_appended_caller_value(self): + """client.py.jinja: default User-Agent is sent once; a caller value of any casing is appended.""" + ua = upcloud_api.client.USER_AGENT + self.assertTrue(ua.startswith("upcloud-python-api/")) + with Client() as client: + self.assertEqual(client.get_httpx_client().headers.get_list("user-agent"), [ua]) + for name in ("User-Agent", "user-agent", "uSeR-aGeNt"): + with self.subTest(header=name): + with Client().with_headers({name: "custom/1.0"}) as client: + self.assertEqual( + client.get_httpx_client().headers.get_list("user-agent"), + [f"{ua} custom/1.0"], + ) + with self.subTest(header="blank"): + with Client().with_headers({"User-Agent": " \t "}) as client: + self.assertEqual(client.get_httpx_client().headers.get_list("user-agent"), [ua]) + + def test_with_headers_keeps_user_agent_on_initialized_client(self): + """client.py.jinja: with_headers appends a User-Agent value on an initialized client.""" + ua = upcloud_api.client.USER_AGENT + client = Client() + http_client = client.get_httpx_client() + client.with_headers({"User-Agent": "custom/1.0"}) + self.assertEqual(http_client.headers.get_list("user-agent"), [f"{ua} custom/1.0"]) + + def test_with_headers_keeps_existing_headers_on_custom_client(self): + """client.py.jinja: with_headers keeps headers of a custom httpx client and appends User-Agent.""" + client = Client().set_httpx_client( + httpx.Client(headers={"Authorization": "Bearer token", "User-Agent": "base/1.0"}) + ) + client.with_headers({"X-Test": "1", "user-agent": "custom/1.0"}) + http_client = client.get_httpx_client() + self.assertEqual(http_client.headers["Authorization"], "Bearer token") + self.assertEqual(http_client.headers["X-Test"], "1") + self.assertEqual(http_client.headers.get_list("user-agent"), ["base/1.0 custom/1.0"]) + + def test_with_headers_appends_user_agent_across_clients(self): + """client.py.jinja: a client from with_headers keeps earlier appended User-Agent values.""" + ua = upcloud_api.client.USER_AGENT + client = Client().with_headers({"User-Agent": "first"}) + updated = client.with_headers({"User-Agent": "second"}) + with updated: + self.assertEqual( + updated.get_httpx_client().headers.get_list("user-agent"), [f"{ua} first second"] + ) + def test_empty_string_unions_parse_both_branches(self): """Empty-string union members do not shadow the other branch.""" server = { diff --git a/upcloud_api/client.py b/upcloud_api/client.py index 85447d3..244b537 100644 --- a/upcloud_api/client.py +++ b/upcloud_api/client.py @@ -1,9 +1,33 @@ +import importlib.metadata import ssl +from collections.abc import Mapping from typing import Any import httpx from attrs import define, evolve, field +try: + USER_AGENT = f"upcloud-python-api/{importlib.metadata.version('upcloud-api')}" +except importlib.metadata.PackageNotFoundError: + USER_AGENT = "upcloud-python-api/unknown" + + +def _apply_headers(current: httpx.Headers, headers: Mapping[str, str]) -> httpx.Headers: + """Copy current headers and apply new ones. A User-Agent value is appended to the current one""" + merged = httpx.Headers(current) + for name, value in headers.items(): + if name.lower() != "user-agent": + merged[name] = value + elif caller := value.strip(" \t"): + base = merged.get("User-Agent") + merged["User-Agent"] = f"{base} {caller}" if base else caller + return merged + + +def _request_headers(headers: Mapping[str, str]) -> httpx.Headers: + """Build request headers on top of the SDK User-Agent""" + return _apply_headers(httpx.Headers({"User-Agent": USER_AGENT}), headers) + @define class Client: @@ -15,7 +39,7 @@ class Client: ``cookies``: A dictionary of cookies to be sent with every request - ``headers``: A dictionary of headers to be sent with every request + ``headers``: A dictionary of headers to be sent with every request. A ``User-Agent`` value is appended to the SDK default. ``timeout``: The maximum amount of a time a request can take. API functions will raise httpx.TimeoutException if this is exceeded. @@ -47,11 +71,12 @@ class Client: def with_headers(self, headers: dict[str, str]) -> "Client": """Get a new client matching this one with additional headers""" + evolved = _apply_headers(httpx.Headers(self._headers), headers) if self._client is not None: - self._client.headers.update(headers) + self._client.headers = _apply_headers(self._client.headers, headers) if self._async_client is not None: - self._async_client.headers.update(headers) - return evolve(self, headers={**self._headers, **headers}) + self._async_client.headers = _apply_headers(self._async_client.headers, headers) + return evolve(self, headers=dict(evolved)) def with_cookies(self, cookies: dict[str, str]) -> "Client": """Get a new client matching this one with additional cookies""" @@ -83,7 +108,7 @@ def get_httpx_client(self) -> httpx.Client: self._client = httpx.Client( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, @@ -114,7 +139,7 @@ def get_async_httpx_client(self) -> httpx.AsyncClient: self._async_client = httpx.AsyncClient( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, @@ -142,7 +167,7 @@ class AuthenticatedClient: ``cookies``: A dictionary of cookies to be sent with every request - ``headers``: A dictionary of headers to be sent with every request + ``headers``: A dictionary of headers to be sent with every request. A ``User-Agent`` value is appended to the SDK default. ``timeout``: The maximum amount of a time a request can take. API functions will raise httpx.TimeoutException if this is exceeded. @@ -181,11 +206,12 @@ class AuthenticatedClient: def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient": """Get a new client matching this one with additional headers""" + evolved = _apply_headers(httpx.Headers(self._headers), headers) if self._client is not None: - self._client.headers.update(headers) + self._client.headers = _apply_headers(self._client.headers, headers) if self._async_client is not None: - self._async_client.headers.update(headers) - return evolve(self, headers={**self._headers, **headers}) + self._async_client.headers = _apply_headers(self._async_client.headers, headers) + return evolve(self, headers=dict(evolved)) def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient": """Get a new client matching this one with additional cookies""" @@ -218,7 +244,7 @@ def get_httpx_client(self) -> httpx.Client: self._client = httpx.Client( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, @@ -250,7 +276,7 @@ def get_async_httpx_client(self) -> httpx.AsyncClient: self._async_client = httpx.AsyncClient( base_url=self._base_url, cookies=self._cookies, - headers=self._headers, + headers=_request_headers(self._headers), timeout=self._timeout, verify=self._verify_ssl, follow_redirects=self._follow_redirects, From ce233eaa050bc5e813867318b0a690591746f913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20V=C3=A4lim=C3=A4ki?= Date: Fri, 20 Nov 2026 11:39:43 +0200 Subject: [PATCH 2/2] fix(client): send User-Agent on custom httpx clients --- generator/templates/client.py.jinja | 12 ++++++++ tests/test_sdk_smoke.py | 47 +++++++++++++++++++++++++++++ upcloud_api/client.py | 18 +++++++++++ 3 files changed, 77 insertions(+) diff --git a/generator/templates/client.py.jinja b/generator/templates/client.py.jinja index adfcc26..06cb482 100644 --- a/generator/templates/client.py.jinja +++ b/generator/templates/client.py.jinja @@ -29,6 +29,12 @@ def _request_headers(headers: Mapping[str, str]) -> httpx.Headers: return _apply_headers(httpx.Headers({"User-Agent": USER_AGENT}), headers) +def _with_sdk_user_agent(client: httpx.Client | httpx.AsyncClient) -> None: + """Set the SDK User-Agent on a caller's client that has no custom User-Agent""" + if client.headers.get("User-Agent") in (None, f"python-httpx/{httpx.__version__}"): + client.headers["User-Agent"] = USER_AGENT + + {% set attrs_info = { "raise_on_unexpected_status": namespace( type="bool", @@ -127,7 +133,10 @@ class Client: """Manually set the underlying httpx.Client **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(client) self._client = client return self @@ -161,7 +170,10 @@ class Client: """Manually set the underlying httpx.AsyncClient **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(async_client) self._async_client = async_client return self diff --git a/tests/test_sdk_smoke.py b/tests/test_sdk_smoke.py index 82cc39a..09f185c 100644 --- a/tests/test_sdk_smoke.py +++ b/tests/test_sdk_smoke.py @@ -217,6 +217,53 @@ def test_with_headers_appends_user_agent_across_clients(self): updated.get_httpx_client().headers.get_list("user-agent"), [f"{ua} first second"] ) + def test_custom_client_gets_sdk_user_agent_unless_custom(self): + """client.py.jinja: set_httpx_client sends the SDK User-Agent unless the caller set one.""" + ua = upcloud_api.client.USER_AGENT + seen: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request.headers["user-agent"]) + return httpx.Response(200) + + with self.subTest(client="default httpx.Client"): + client = Client().set_httpx_client( + httpx.Client(transport=httpx.MockTransport(handler)) + ) + client.get_httpx_client().get("https://example.test/") + self.assertEqual(seen[-1], ua) + with self.subTest(client="deleted User-Agent"): + http_client = httpx.Client(transport=httpx.MockTransport(handler)) + del http_client.headers["User-Agent"] + client = Client().set_httpx_client(http_client) + client.get_httpx_client().get("https://example.test/") + self.assertEqual(seen[-1], ua) + with self.subTest(client="custom User-Agent"): + client = Client().set_httpx_client( + httpx.Client( + transport=httpx.MockTransport(handler), headers={"User-Agent": "base/1.0"} + ) + ) + client.get_httpx_client().get("https://example.test/") + self.assertEqual(seen[-1], "base/1.0") + + async def send_async(headers: dict[str, str]) -> str: + async def async_handler(request: httpx.Request) -> httpx.Response: + seen.append(request.headers["user-agent"]) + return httpx.Response(200) + + async_client = httpx.AsyncClient( + transport=httpx.MockTransport(async_handler), headers=headers + ) + client = Client().set_async_httpx_client(async_client) + await client.get_async_httpx_client().get("https://example.test/") + return seen[-1] + + with self.subTest(client="default httpx.AsyncClient"): + self.assertEqual(asyncio.run(send_async({})), ua) + with self.subTest(client="custom User-Agent on httpx.AsyncClient"): + self.assertEqual(asyncio.run(send_async({"User-Agent": "base/1.0"})), "base/1.0") + def test_empty_string_unions_parse_both_branches(self): """Empty-string union members do not shadow the other branch.""" server = { diff --git a/upcloud_api/client.py b/upcloud_api/client.py index 244b537..6904099 100644 --- a/upcloud_api/client.py +++ b/upcloud_api/client.py @@ -29,6 +29,12 @@ def _request_headers(headers: Mapping[str, str]) -> httpx.Headers: return _apply_headers(httpx.Headers({"User-Agent": USER_AGENT}), headers) +def _with_sdk_user_agent(client: httpx.Client | httpx.AsyncClient) -> None: + """Set the SDK User-Agent on a caller's client that has no custom User-Agent""" + if client.headers.get("User-Agent") in (None, f"python-httpx/{httpx.__version__}"): + client.headers["User-Agent"] = USER_AGENT + + @define class Client: """A class for keeping track of data related to the API @@ -98,7 +104,10 @@ def set_httpx_client(self, client: httpx.Client) -> "Client": """Manually set the underlying httpx.Client **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(client) self._client = client return self @@ -129,7 +138,10 @@ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client": """Manually set the underlying httpx.AsyncClient **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(async_client) self._async_client = async_client return self @@ -233,7 +245,10 @@ def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient": """Manually set the underlying httpx.Client **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(client) self._client = client return self @@ -265,7 +280,10 @@ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Authentica """Manually set the underlying httpx.AsyncClient **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + + The SDK User-Agent is set on the client in place unless it already has a custom User-Agent. """ + _with_sdk_user_agent(async_client) self._async_client = async_client return self