Skip to content

Commit 97f9e14

Browse files
Support optional JSON headers via environment config
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 4ba8b73 commit 97f9e14

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

hyperbrowser/config.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from dataclasses import dataclass
2+
import json
23
from typing import Dict, Mapping, Optional
34
import os
45

@@ -49,4 +50,18 @@ def from_env(cls) -> "ClientConfig":
4950
base_url = os.environ.get(
5051
"HYPERBROWSER_BASE_URL", "https://api.hyperbrowser.ai"
5152
)
52-
return cls(api_key=api_key, base_url=base_url)
53+
headers = None
54+
raw_headers = os.environ.get("HYPERBROWSER_HEADERS")
55+
if raw_headers:
56+
try:
57+
parsed_headers = json.loads(raw_headers)
58+
except json.JSONDecodeError as exc:
59+
raise HyperbrowserError(
60+
"HYPERBROWSER_HEADERS must be valid JSON object"
61+
) from exc
62+
if not isinstance(parsed_headers, dict):
63+
raise HyperbrowserError(
64+
"HYPERBROWSER_HEADERS must be a JSON object of string pairs"
65+
)
66+
headers = parsed_headers
67+
return cls(api_key=api_key, base_url=base_url, headers=headers)

tests/test_config.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,36 @@ def test_client_config_from_env_reads_api_key_and_base_url(monkeypatch):
3232
assert config.base_url == "https://example.local"
3333

3434

35+
def test_client_config_from_env_reads_headers(monkeypatch):
36+
monkeypatch.setenv("HYPERBROWSER_API_KEY", "test-key")
37+
monkeypatch.setenv("HYPERBROWSER_HEADERS", '{"X-Request-Id":"abc123"}')
38+
39+
config = ClientConfig.from_env()
40+
41+
assert config.headers == {"X-Request-Id": "abc123"}
42+
43+
44+
def test_client_config_from_env_rejects_invalid_headers_json(monkeypatch):
45+
monkeypatch.setenv("HYPERBROWSER_API_KEY", "test-key")
46+
monkeypatch.setenv("HYPERBROWSER_HEADERS", "{invalid")
47+
48+
with pytest.raises(
49+
HyperbrowserError, match="HYPERBROWSER_HEADERS must be valid JSON object"
50+
):
51+
ClientConfig.from_env()
52+
53+
54+
def test_client_config_from_env_rejects_non_object_headers_json(monkeypatch):
55+
monkeypatch.setenv("HYPERBROWSER_API_KEY", "test-key")
56+
monkeypatch.setenv("HYPERBROWSER_HEADERS", '["not-an-object"]')
57+
58+
with pytest.raises(
59+
HyperbrowserError,
60+
match="HYPERBROWSER_HEADERS must be a JSON object of string pairs",
61+
):
62+
ClientConfig.from_env()
63+
64+
3565
def test_client_config_from_env_normalizes_base_url(monkeypatch):
3666
monkeypatch.setenv("HYPERBROWSER_API_KEY", "test-key")
3767
monkeypatch.setenv("HYPERBROWSER_BASE_URL", " https://example.local/ ")

0 commit comments

Comments
 (0)