Skip to content

feat: Add support for additional headers in API requests #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 19, 2025
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 src/typesense/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ class ConfigDict(typing.TypedDict):
master_node (typing.Union[str, NodeConfigDict], deprecated): A dictionary or
URL that represents the master node.

additional_headers (dict): Additional headers to include in the request.

read_replica_nodes (list[typing.Union[str, NodeConfigDict]], deprecated): A list of
dictionaries or URLs that represent the read replica nodes.
"""
Expand All @@ -87,6 +89,7 @@ class ConfigDict(typing.TypedDict):
verify: typing.NotRequired[bool]
timeout_seconds: typing.NotRequired[int] # deprecated
master_node: typing.NotRequired[typing.Union[str, NodeConfigDict]] # deprecated
additional_headers: typing.NotRequired[typing.Dict[str, str]]
read_replica_nodes: typing.NotRequired[
typing.List[typing.Union[str, NodeConfigDict]]
] # deprecated
Expand Down Expand Up @@ -213,6 +216,7 @@ def __init__(
60,
)
self.verify = config_dict.get("verify", True)
self.additional_headers = config_dict.get("additional_headers", {})

def _handle_nearest_node(
self,
Expand Down
6 changes: 5 additions & 1 deletion src/typesense/request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,11 @@ def make_request(
Raises:
TypesenseClientError: If the API returns an error response.
"""
headers = {self.api_key_header_name: self.config.api_key}
headers = {
self.api_key_header_name: self.config.api_key,
}
headers.update(self.config.additional_headers)

kwargs.setdefault("headers", {}).update(headers)
kwargs.setdefault("timeout", self.config.connection_timeout_seconds)
kwargs.setdefault("verify", self.config.verify)
Expand Down
42 changes: 41 additions & 1 deletion tests/api_call_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import sys
import time

from isort import Config
from pytest_mock import MockFixture

if sys.version_info >= (3, 11):
Expand Down Expand Up @@ -135,6 +136,43 @@ def test_normalize_params_with_no_booleans() -> None:
assert parameter_dict == {"key1": "value", "key2": 123}


def test_additional_headers(fake_api_call: ApiCall) -> None:
"""Test the `make_request` method with additional headers from the config."""
session = requests.sessions.Session()
api_call = ApiCall(
Configuration(
{
"additional_headers": {
"AdditionalHeader1": "test",
"AdditionalHeader2": "test2",
},
"api_key": "test-api",
"nodes": [
"http://nearest:8108",
],
},
),
)

with requests_mock.mock(session=session) as request_mocker:
request_mocker.get(
"http://nearest:8108/test",
json={"key": "value"},
status_code=200,
)

api_call._execute_request(
session.get,
"/test",
as_json=True,
entity_type=typing.Dict[str, str],
)

request = request_mocker.request_history[-1]
assert request.headers["AdditionalHeader1"] == "test"
assert request.headers["AdditionalHeader2"] == "test2"


def test_make_request_as_json(fake_api_call: ApiCall) -> None:
"""Test the `make_request` method with JSON response."""
session = requests.sessions.Session()
Expand Down Expand Up @@ -172,6 +210,7 @@ def test_make_request_as_text(fake_api_call: ApiCall) -> None:
as_json=False,
entity_type=typing.Dict[str, str],
)

assert response == "response text"


Expand Down Expand Up @@ -431,7 +470,8 @@ def test_get_node_no_healthy_nodes(
assert "No healthy nodes were found. Returning the next node." in caplog.text

assert (
selected_node == fake_api_call.node_manager.nodes[fake_api_call.node_manager.node_index]
selected_node
== fake_api_call.node_manager.nodes[fake_api_call.node_manager.node_index]
)

assert fake_api_call.node_manager.node_index == 0
Expand Down
2 changes: 2 additions & 0 deletions tests/configuration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def test_configuration_explicit() -> None:
"num_retries": 5,
"retry_interval_seconds": 2.0,
"verify": False,
"additional_headers": {"X-Test": "test", "X-Test2": "test2"},
}

configuration = Configuration(config)
Expand All @@ -82,6 +83,7 @@ def test_configuration_explicit() -> None:
"num_retries": 5,
"retry_interval_seconds": 2.0,
"verify": False,
"additional_headers": {"X-Test": "test", "X-Test2": "test2"},
}

assert_to_contain_object(configuration, expected)
Expand Down