Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<version>`. A `User-Agent` value in `headers` is appended to it.

## [3.0.0a1] - 2026-10-14

### Changed
Expand Down
49 changes: 43 additions & 6 deletions generator/templates/client.py.jinja
Original file line number Diff line number Diff line change
@@ -1,9 +1,39 @@
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)


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(
Expand Down Expand Up @@ -41,7 +71,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.
Expand Down Expand Up @@ -75,11 +105,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"""
Expand All @@ -102,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

Expand All @@ -115,7 +149,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,
Expand All @@ -136,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

Expand All @@ -149,7 +186,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,
Expand Down
93 changes: 93 additions & 0 deletions tests/test_sdk_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,99 @@ 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_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 = {
Expand Down
68 changes: 56 additions & 12 deletions upcloud_api/client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,39 @@
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)


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:
Expand All @@ -15,7 +45,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.
Expand Down Expand Up @@ -47,11 +77,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"""
Expand All @@ -73,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

Expand All @@ -83,7 +117,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,
Expand All @@ -104,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

Expand All @@ -114,7 +151,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,
Expand Down Expand Up @@ -142,7 +179,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.
Expand Down Expand Up @@ -181,11 +218,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"""
Expand All @@ -207,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

Expand All @@ -218,7 +259,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,
Expand All @@ -239,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

Expand All @@ -250,7 +294,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,
Expand Down
Loading