Coverage for src\baobab_web_api_caller\auth\api_key_query_authentication_strategy.py: 95%
29 statements
« prev ^ index » next coverage.py v7.10.3, created at 2026-03-21 12:10 +0100
« prev ^ index » next coverage.py v7.10.3, created at 2026-03-21 12:10 +0100
1"""Stratégie API key via query parameters."""
3from __future__ import annotations
5from dataclasses import dataclass
7from baobab_web_api_caller.auth.authentication_strategy import AuthenticationStrategy
8from baobab_web_api_caller.core.baobab_request import BaobabRequest
9from baobab_web_api_caller.exceptions.configuration_exception import ConfigurationException
12@dataclass(frozen=True, slots=True)
13class ApiKeyQueryAuthenticationStrategy(AuthenticationStrategy):
14 """Ajoute une API key dans les query params.
16 :param param_name: Nom du paramètre.
17 :type param_name: str
18 :param api_key: Valeur de la clé.
19 :type api_key: str
20 :raises ConfigurationException: Si les paramètres sont invalides.
21 """
23 param_name: str
24 api_key: str
26 def __post_init__(self) -> None:
27 if not isinstance(self.param_name, str) or self.param_name.strip() == "":
28 raise ConfigurationException("param_name must be a non-empty string")
29 if not isinstance(self.api_key, str) or self.api_key.strip() == "":
30 raise ConfigurationException("api_key must be a non-empty string")
31 if " " in self.param_name: 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true
32 raise ConfigurationException("param_name must not contain spaces")
34 def apply(self, request: BaobabRequest) -> BaobabRequest:
35 """Ajoute/écrase le paramètre API key."""
37 query_params: dict[str, str | list[str]] = {}
38 for key, value in request.query_params.items():
39 if isinstance(value, str):
40 query_params[key] = value
41 else:
42 query_params[key] = list(value)
44 existing = query_params.get(self.param_name)
45 if existing is None:
46 query_params[self.param_name] = self.api_key
47 elif isinstance(existing, str):
48 query_params[self.param_name] = [existing, self.api_key]
49 else:
50 existing.append(self.api_key)
52 return BaobabRequest(
53 method=request.method,
54 path=request.path,
55 query_params=query_params,
56 headers=request.headers,
57 json_body=request.json_body,
58 form_body=request.form_body,
59 timeout_seconds=request.timeout_seconds,
60 )