eq-api-connector 1.2.2__tar.gz → 1.2.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {eq_api_connector-1.2.2 → eq_api_connector-1.2.4}/PKG-INFO +36 -1
- eq_api_connector-1.2.4/README.md +69 -0
- {eq_api_connector-1.2.2 → eq_api_connector-1.2.4}/pyproject.toml +2 -1
- {eq_api_connector-1.2.2 → eq_api_connector-1.2.4}/pyproject.toml.orig +2 -1
- eq_api_connector-1.2.4/src/eq_api_connector/connector.py +578 -0
- eq_api_connector-1.2.2/src/eq_api_connector/connector.py → eq_api_connector-1.2.4/src/eq_api_connector/connector.py.orig +19 -0
- eq_api_connector-1.2.2/README.md +0 -35
- {eq_api_connector-1.2.2 → eq_api_connector-1.2.4}/src/eq_api_connector/__init__.py +0 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: eq-api-connector
|
|
3
|
-
Version: 1.2.
|
|
3
|
+
Version: 1.2.4
|
|
4
4
|
Summary: API connector (API SDK) to connect to public client app registrations using delegated permissions (MSAL).
|
|
5
5
|
Author: Åsmund Våge Fannemel
|
|
6
6
|
Author-email: Åsmund Våge Fannemel <asmf@equinor.com>
|
|
7
7
|
License: MIT
|
|
8
8
|
Requires-Dist: requests>=2.34.2,<3.0.0
|
|
9
|
+
Requires-Dist: urllib3>=1.26.5,<3.0.0
|
|
9
10
|
Requires-Dist: msal-bearer>=1.6.1,<2.0.0
|
|
10
11
|
Requires-Python: >=3.10, <4.0
|
|
11
12
|
Description-Content-Type: text/markdown
|
|
@@ -45,3 +46,37 @@ When a token is supplied, `APIConnector` uses it as-is and does not check its ex
|
|
|
45
46
|
|
|
46
47
|
Typically packages using eq-api-connector should subclass the APIConnector or keep a singleton a reference.
|
|
47
48
|
|
|
49
|
+
GET requests retry up to three times after connection or response-read failures,
|
|
50
|
+
or transient HTTP statuses (429, 500, 502, 503, and 504), with exponential
|
|
51
|
+
backoff. POSTs are not retried after transmission; connection-establishment
|
|
52
|
+
attempts can retry before the request is sent.
|
|
53
|
+
|
|
54
|
+
## Optional API Subscription Key (APIM)
|
|
55
|
+
|
|
56
|
+
Some APIs require an API subscription key (called an APIM key in Equinor) in
|
|
57
|
+
addition to MSAL sign-in. Pass it as `subscription_key`:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import os
|
|
61
|
+
from eq_api_connector import APIConnector
|
|
62
|
+
|
|
63
|
+
c = APIConnector(
|
|
64
|
+
client_id=client_id,
|
|
65
|
+
scope=scope,
|
|
66
|
+
subscription_key=os.getenv("APIM_SUBSCRIPTION_KEY"),
|
|
67
|
+
)
|
|
68
|
+
c.url_prod = url_prod
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
When set, the key is sent as the `Ocp-Apim-Subscription-Key` header for all
|
|
72
|
+
requests, including concurrent reads, downloads and uploads. Omitting it leaves
|
|
73
|
+
the existing bearer-token authentication unchanged; MSAL authentication is still
|
|
74
|
+
required. The connector does not automatically read environment variables or
|
|
75
|
+
retrieve keys from Azure Key Vault.
|
|
76
|
+
|
|
77
|
+
Use `c.subscription_key = new_key` to replace the key, or
|
|
78
|
+
`c.subscription_key = None` (or `""`) to remove it. Only use the connector with
|
|
79
|
+
trusted API URLs and redirect destinations, since its session carries the key.
|
|
80
|
+
Store keys outside source code, for example in an environment variable or a
|
|
81
|
+
secret store. Do not commit keys or log request headers containing them.
|
|
82
|
+
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# eq-api-connector
|
|
2
|
+
A small python package to handle authentication and act as a generic api sdk.
|
|
3
|
+
|
|
4
|
+
It supports apis Public client applications using [acquire_token_interactive](https://learn.microsoft.com/en-us/python/api/msal/msal.application.publicclientapplication?view=msal-py-latest#msal-application-publicclientapplication-acquire-token-interactive) and contains a few basic endpoint accessors.
|
|
5
|
+
|
|
6
|
+
# Install
|
|
7
|
+
Install from pypi ```pip install eq-api-connector``` or clone and use ```uv sync``` as a developer.
|
|
8
|
+
|
|
9
|
+
# Usage
|
|
10
|
+
See the dummy example below
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
from eq_api_connector import APIConnector
|
|
14
|
+
|
|
15
|
+
url_prod = "https://api.gateway.equinor.com/dummy/v1"
|
|
16
|
+
client_id = "insert_your_client_id_here" # IOC SME monitoring SDK
|
|
17
|
+
scope = ["34de7368-10f7-4c34-a4df-928156065f2c/ReadWrite"]
|
|
18
|
+
|
|
19
|
+
c = APIConnector(client_id=client_id, scope=scope)
|
|
20
|
+
c.url_prod = url_prod
|
|
21
|
+
|
|
22
|
+
model_owners = c.get_json("/example-endpoint")
|
|
23
|
+
````
|
|
24
|
+
|
|
25
|
+
If you already have an access token, pass it with `token`:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
access_token = get_access_token_from_your_auth_flow()
|
|
29
|
+
c = APIConnector(token=access_token)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
When a token is supplied, `APIConnector` uses it as-is and does not check its expiry or refresh it. The caller is responsible for obtaining and supplying a fresh token when it expires.
|
|
33
|
+
|
|
34
|
+
Typically packages using eq-api-connector should subclass the APIConnector or keep a singleton a reference.
|
|
35
|
+
|
|
36
|
+
GET requests retry up to three times after connection or response-read failures,
|
|
37
|
+
or transient HTTP statuses (429, 500, 502, 503, and 504), with exponential
|
|
38
|
+
backoff. POSTs are not retried after transmission; connection-establishment
|
|
39
|
+
attempts can retry before the request is sent.
|
|
40
|
+
|
|
41
|
+
## Optional API Subscription Key (APIM)
|
|
42
|
+
|
|
43
|
+
Some APIs require an API subscription key (called an APIM key in Equinor) in
|
|
44
|
+
addition to MSAL sign-in. Pass it as `subscription_key`:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import os
|
|
48
|
+
from eq_api_connector import APIConnector
|
|
49
|
+
|
|
50
|
+
c = APIConnector(
|
|
51
|
+
client_id=client_id,
|
|
52
|
+
scope=scope,
|
|
53
|
+
subscription_key=os.getenv("APIM_SUBSCRIPTION_KEY"),
|
|
54
|
+
)
|
|
55
|
+
c.url_prod = url_prod
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
When set, the key is sent as the `Ocp-Apim-Subscription-Key` header for all
|
|
59
|
+
requests, including concurrent reads, downloads and uploads. Omitting it leaves
|
|
60
|
+
the existing bearer-token authentication unchanged; MSAL authentication is still
|
|
61
|
+
required. The connector does not automatically read environment variables or
|
|
62
|
+
retrieve keys from Azure Key Vault.
|
|
63
|
+
|
|
64
|
+
Use `c.subscription_key = new_key` to replace the key, or
|
|
65
|
+
`c.subscription_key = None` (or `""`) to remove it. Only use the connector with
|
|
66
|
+
trusted API URLs and redirect destinations, since its session carries the key.
|
|
67
|
+
Store keys outside source code, for example in an environment variable or a
|
|
68
|
+
secret store. Do not commit keys or log request headers containing them.
|
|
69
|
+
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "eq-api-connector"
|
|
3
|
-
version = "1.2.
|
|
3
|
+
version = "1.2.4"
|
|
4
4
|
description = "API connector (API SDK) to connect to public client app registrations using delegated permissions (MSAL)."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.10,<4.0"
|
|
7
7
|
dependencies = [
|
|
8
8
|
"requests (>=2.34.2,<3.0.0)",
|
|
9
|
+
"urllib3 (>=1.26.5,<3.0.0)",
|
|
9
10
|
"msal-bearer (>=1.6.1,<2.0.0)",
|
|
10
11
|
]
|
|
11
12
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "eq-api-connector"
|
|
3
|
-
version = "1.2.
|
|
3
|
+
version = "1.2.4"
|
|
4
4
|
description = "API connector (API SDK) to connect to public client app registrations using delegated permissions (MSAL)."
|
|
5
5
|
authors = [
|
|
6
6
|
{name = "Åsmund Våge Fannemel",email = "asmf@equinor.com"}
|
|
@@ -10,6 +10,7 @@ readme = "README.md"
|
|
|
10
10
|
requires-python = ">=3.10,<4.0"
|
|
11
11
|
dependencies = [
|
|
12
12
|
"requests (>=2.34.2,<3.0.0)",
|
|
13
|
+
"urllib3 (>=1.26.5,<3.0.0)",
|
|
13
14
|
"msal-bearer (>=1.6.1,<2.0.0)",
|
|
14
15
|
]
|
|
15
16
|
|
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import warnings
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from io import BytesIO
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
from requests.adapters import DEFAULT_POOLSIZE, HTTPAdapter
|
|
13
|
+
from urllib3.util.retry import Retry
|
|
14
|
+
|
|
15
|
+
from msal_bearer import Authenticator, get_user_name
|
|
16
|
+
|
|
17
|
+
_eq_tenant_id = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0"
|
|
18
|
+
_eq_domain = "equinor.com"
|
|
19
|
+
DEFAULT_TIMEOUT = (5.0, 60.0)
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_object_from_json(
|
|
25
|
+
text: Union[str, List[str]],
|
|
26
|
+
):
|
|
27
|
+
if isinstance(text, list):
|
|
28
|
+
obj = [json.loads(x, object_hook=lambda d: SimpleNamespace(**d)) for x in text]
|
|
29
|
+
else:
|
|
30
|
+
obj = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
|
|
31
|
+
return obj
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Connector(ABC):
|
|
35
|
+
"""Abstract base class for API connectors. Contains common functionality for API connectors, such as handling of API URLs and authentication."""
|
|
36
|
+
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self._use_dev = False
|
|
39
|
+
self._url_prod = ""
|
|
40
|
+
self._url_dev = ""
|
|
41
|
+
self._authenticator: Optional[Authenticator] = None
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def url_prod(self) -> str:
|
|
45
|
+
return self._url_prod
|
|
46
|
+
|
|
47
|
+
@url_prod.setter
|
|
48
|
+
def url_prod(self, url: str) -> None:
|
|
49
|
+
self._url_prod = url
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def url_dev(self) -> str:
|
|
53
|
+
return self._url_dev
|
|
54
|
+
|
|
55
|
+
@url_dev.setter
|
|
56
|
+
def url_dev(self, url: str) -> None:
|
|
57
|
+
self._url_dev = url
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def use_dev(self) -> bool:
|
|
61
|
+
return self._use_dev
|
|
62
|
+
|
|
63
|
+
@use_dev.setter
|
|
64
|
+
def use_dev(self, use_dev: bool) -> None:
|
|
65
|
+
if not isinstance(use_dev, bool):
|
|
66
|
+
raise TypeError("Input use_dev shall be boolean.")
|
|
67
|
+
self._use_dev = use_dev
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def url(self) -> str:
|
|
71
|
+
"""Return development URL when enabled, otherwise production URL."""
|
|
72
|
+
if self.use_dev:
|
|
73
|
+
return self._url_dev
|
|
74
|
+
return self._url_prod
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def authenticator(self) -> Optional[Authenticator]:
|
|
78
|
+
return self._authenticator
|
|
79
|
+
|
|
80
|
+
@authenticator.setter
|
|
81
|
+
def authenticator(self, authenticator: Optional[Authenticator]) -> None:
|
|
82
|
+
if authenticator is not None and not isinstance(authenticator, Authenticator):
|
|
83
|
+
raise TypeError("Input authenticator shall be of type Authenticator.")
|
|
84
|
+
self._authenticator = authenticator
|
|
85
|
+
|
|
86
|
+
def set_url_prod(self, url: str) -> None:
|
|
87
|
+
"""Setter for property _url_prod.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
url (str): URL to set.
|
|
91
|
+
"""
|
|
92
|
+
warnings.warn(
|
|
93
|
+
"set_url_prod() is deprecated; use the url_prod property instead.",
|
|
94
|
+
DeprecationWarning,
|
|
95
|
+
stacklevel=2,
|
|
96
|
+
)
|
|
97
|
+
self.url_prod = url
|
|
98
|
+
|
|
99
|
+
def set_url_dev(self, url: str) -> None:
|
|
100
|
+
"""Setter for property _url_dev.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
url (str): URL to set.
|
|
104
|
+
"""
|
|
105
|
+
warnings.warn(
|
|
106
|
+
"set_url_dev() is deprecated; use the url_dev property instead.",
|
|
107
|
+
DeprecationWarning,
|
|
108
|
+
stacklevel=2,
|
|
109
|
+
)
|
|
110
|
+
self.url_dev = url
|
|
111
|
+
|
|
112
|
+
def set_use_dev(self, use_dev: bool) -> None:
|
|
113
|
+
"""Setter for global property _use_dev.
|
|
114
|
+
If _use_dev is True, the API URL will be set to the development URL,
|
|
115
|
+
otherwise it will be set to the production URL.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
use_dev (bool): Value to set _use_dev to.
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
TypeError: In case input use_dev is not a boolean.
|
|
122
|
+
"""
|
|
123
|
+
warnings.warn(
|
|
124
|
+
"set_use_dev() is deprecated; use the use_dev property instead.",
|
|
125
|
+
DeprecationWarning,
|
|
126
|
+
stacklevel=2,
|
|
127
|
+
)
|
|
128
|
+
self.use_dev = use_dev
|
|
129
|
+
|
|
130
|
+
def get_url(self) -> str:
|
|
131
|
+
"""Getter for URL. Will return the dev URL if _use_dev is True, otherwise will return the production URL.
|
|
132
|
+
Returns:
|
|
133
|
+
str: API URL
|
|
134
|
+
"""
|
|
135
|
+
warnings.warn(
|
|
136
|
+
"get_url() is deprecated; use the url property instead.",
|
|
137
|
+
DeprecationWarning,
|
|
138
|
+
stacklevel=2,
|
|
139
|
+
)
|
|
140
|
+
return self.url
|
|
141
|
+
|
|
142
|
+
def set_Authenticator(self, authenticator: Optional[Authenticator]) -> None:
|
|
143
|
+
"""Setter for property authenticator.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
authenticator (Authenticator): Authenticator to set.
|
|
147
|
+
"""
|
|
148
|
+
warnings.warn(
|
|
149
|
+
"set_Authenticator() is deprecated; use the authenticator property instead.",
|
|
150
|
+
DeprecationWarning,
|
|
151
|
+
stacklevel=2,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
if not isinstance(authenticator, Authenticator):
|
|
155
|
+
raise TypeError("Input authenticator shall be of type Authenticator.")
|
|
156
|
+
|
|
157
|
+
self.authenticator = authenticator
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class APIConnector(Connector):
|
|
161
|
+
"""API connector class. Inherits from Connector. Contains functionality for connecting to APIs using MSAL authentication."""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
tenant_id: Optional[str] = _eq_tenant_id,
|
|
166
|
+
client_id: Optional[str] = None,
|
|
167
|
+
client_secret: Optional[str] = None,
|
|
168
|
+
scope: Optional[Union[List[str], str]] = None,
|
|
169
|
+
user_name: Optional[str] = None,
|
|
170
|
+
user_assertion: Optional[str] = None,
|
|
171
|
+
token: Optional[str] = None,
|
|
172
|
+
subscription_key: Optional[str] = None,
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Initialize the API connector.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
tenant_id: Tenant ID passed to Authenticator. Defaults to Equinor's
|
|
178
|
+
tenant ID. Used only when an Authenticator is created.
|
|
179
|
+
client_id: Client application ID passed to Authenticator. If this or
|
|
180
|
+
scope is provided, an Authenticator is created.
|
|
181
|
+
client_secret: Optional client secret passed to Authenticator when
|
|
182
|
+
non-empty.
|
|
183
|
+
scope: One scope or a list of scopes passed to Authenticator. If this
|
|
184
|
+
or client_id is provided, an Authenticator is created.
|
|
185
|
+
user_name: Username passed to Authenticator. Defaults to the current
|
|
186
|
+
user; if it does not contain "@", "@equinor.com" is appended.
|
|
187
|
+
user_assertion: Optional user assertion passed to Authenticator.
|
|
188
|
+
token: Optional externally obtained access token. When supplied, it
|
|
189
|
+
takes precedence over the Authenticator token. It is used as-is
|
|
190
|
+
and is not refreshed automatically when it expires; the caller
|
|
191
|
+
must obtain and supply a fresh token.
|
|
192
|
+
subscription_key: Optional APIM subscription key. When non-empty, it
|
|
193
|
+
is sent in the ``Ocp-Apim-Subscription-Key`` request header.
|
|
194
|
+
|
|
195
|
+
If neither token nor an Authenticator is available, token retrieval and
|
|
196
|
+
authenticated requests raise ValueError.
|
|
197
|
+
"""
|
|
198
|
+
super().__init__()
|
|
199
|
+
self._token = token
|
|
200
|
+
self._raise_for_status = True
|
|
201
|
+
self._session = requests.Session()
|
|
202
|
+
self._pool_maxsize = DEFAULT_POOLSIZE
|
|
203
|
+
adapter = self._create_http_adapter(self._pool_maxsize)
|
|
204
|
+
self._session.mount("https://", adapter)
|
|
205
|
+
self._session.mount("http://", adapter)
|
|
206
|
+
self.subscription_key = subscription_key
|
|
207
|
+
|
|
208
|
+
if user_name is None:
|
|
209
|
+
user_name = f"{get_user_name()}"
|
|
210
|
+
|
|
211
|
+
if "@" not in user_name:
|
|
212
|
+
user_name = f"{user_name}@{_eq_domain}"
|
|
213
|
+
|
|
214
|
+
if client_id or scope:
|
|
215
|
+
a = Authenticator(
|
|
216
|
+
tenant_id=tenant_id,
|
|
217
|
+
client_id=client_id,
|
|
218
|
+
scopes=scope if scope else None,
|
|
219
|
+
client_secret=client_secret if client_secret else None,
|
|
220
|
+
user_name=user_name,
|
|
221
|
+
user_assertion=user_assertion,
|
|
222
|
+
)
|
|
223
|
+
self.authenticator = a
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def session(self) -> requests.Session:
|
|
227
|
+
"""HTTP session shared by all requests, reusing connections between calls."""
|
|
228
|
+
return self._session
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def subscription_key(self) -> Optional[str]:
|
|
232
|
+
"""Optional APIM subscription key, sent in addition to the bearer token."""
|
|
233
|
+
return self._session.headers.get("Ocp-Apim-Subscription-Key")
|
|
234
|
+
|
|
235
|
+
@subscription_key.setter
|
|
236
|
+
def subscription_key(self, subscription_key: Optional[str]) -> None:
|
|
237
|
+
if subscription_key is not None and not isinstance(subscription_key, str):
|
|
238
|
+
raise TypeError("Input subscription_key shall be a string or None.")
|
|
239
|
+
if subscription_key:
|
|
240
|
+
self._session.headers["Ocp-Apim-Subscription-Key"] = subscription_key
|
|
241
|
+
else:
|
|
242
|
+
self._session.headers.pop("Ocp-Apim-Subscription-Key", None)
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def raise_for_status(self) -> bool:
|
|
246
|
+
return self._raise_for_status
|
|
247
|
+
|
|
248
|
+
@raise_for_status.setter
|
|
249
|
+
def raise_for_status(self, raise_for_status: bool) -> None:
|
|
250
|
+
if not isinstance(raise_for_status, bool):
|
|
251
|
+
raise TypeError("Input raise_for_status shall be boolean.")
|
|
252
|
+
self._raise_for_status = raise_for_status
|
|
253
|
+
|
|
254
|
+
def get_token(self) -> str:
|
|
255
|
+
"""Return the supplied token or retrieve one from the authenticator.
|
|
256
|
+
|
|
257
|
+
A supplied token is returned as-is and is not automatically refreshed
|
|
258
|
+
when it expires.
|
|
259
|
+
|
|
260
|
+
Returns:
|
|
261
|
+
str: Access token.
|
|
262
|
+
"""
|
|
263
|
+
if self._token is not None:
|
|
264
|
+
return self._token
|
|
265
|
+
|
|
266
|
+
if not self.authenticator:
|
|
267
|
+
raise ValueError("Authenticator is not set")
|
|
268
|
+
|
|
269
|
+
return self.authenticator.get_token()
|
|
270
|
+
|
|
271
|
+
def set_raise_for_status(self, raise_for_status: bool) -> None:
|
|
272
|
+
"""Setter for property _raise_for_status.
|
|
273
|
+
If _raise_for_status is True, the requests will raise an exception for HTTP errors,
|
|
274
|
+
otherwise it will not.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
raise_for_status (bool): Value to set _raise_for_status to.
|
|
278
|
+
|
|
279
|
+
Raises:
|
|
280
|
+
TypeError: In case input raise_for_status is not a boolean.
|
|
281
|
+
"""
|
|
282
|
+
warnings.warn(
|
|
283
|
+
"set_raise_for_status() is deprecated; use the raise_for_status property instead.",
|
|
284
|
+
DeprecationWarning,
|
|
285
|
+
stacklevel=2,
|
|
286
|
+
)
|
|
287
|
+
self.raise_for_status = raise_for_status
|
|
288
|
+
|
|
289
|
+
def get_json(
|
|
290
|
+
self,
|
|
291
|
+
url: str,
|
|
292
|
+
params: Optional[dict] = None,
|
|
293
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
294
|
+
allow_redirects: bool = True,
|
|
295
|
+
) -> Union[dict, requests.Response, List[dict[str, str]], List[str]]:
|
|
296
|
+
"""Get JSON from API endpoint.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
url (str): Full or partial url to api endpoint. Is prefixed with self.url if url starts with "/".
|
|
300
|
+
params (Optional[dict], optional): Optional endpoint parameters. Defaults to None.
|
|
301
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
302
|
+
allow_redirects (bool, optional): Whether to follow redirects. Defaults to True.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
Union[dict, requests.Response, List[dict[str, str]], List[str]]: Result from response.json()
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
return self._get_json(
|
|
309
|
+
url,
|
|
310
|
+
params,
|
|
311
|
+
self.get_token(),
|
|
312
|
+
timeout=timeout,
|
|
313
|
+
allow_redirects=allow_redirects,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
def get_multiple_json(
|
|
317
|
+
self,
|
|
318
|
+
urls: List[str],
|
|
319
|
+
params: Optional[dict] = None,
|
|
320
|
+
max_workers: int = 8,
|
|
321
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
322
|
+
) -> List[Union[dict, requests.Response, List[dict[str, str]], List[str]]]:
|
|
323
|
+
"""Get JSON from several API endpoints concurrently.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
urls (List[str]): Full or partial urls to api endpoints. Each is prefixed with self.url if it starts with "/".
|
|
327
|
+
params (Optional[dict], optional): Endpoint parameters applied to every request. Defaults to None.
|
|
328
|
+
max_workers (int, optional): Maximum number of concurrent requests. Defaults to 8.
|
|
329
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
List[Union[dict, requests.Response, List[dict[str, str]], List[str]]]: One result per url, in the same order as urls.
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
if max_workers < 1:
|
|
336
|
+
raise ValueError("max_workers shall be at least 1.")
|
|
337
|
+
|
|
338
|
+
if not urls:
|
|
339
|
+
return []
|
|
340
|
+
|
|
341
|
+
token = self.get_token()
|
|
342
|
+
workers = min(max_workers, len(urls))
|
|
343
|
+
self._ensure_pool_size(workers)
|
|
344
|
+
|
|
345
|
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
|
346
|
+
return list(
|
|
347
|
+
executor.map(
|
|
348
|
+
lambda u: self._get_json(u, params, token, timeout=timeout), urls
|
|
349
|
+
)
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
def _ensure_pool_size(self, size: int) -> None:
|
|
353
|
+
# Remounting drops pooled connections, so only grow the pool when needed.
|
|
354
|
+
if size <= self._pool_maxsize:
|
|
355
|
+
return
|
|
356
|
+
adapter = self._create_http_adapter(size)
|
|
357
|
+
self._session.mount("https://", adapter)
|
|
358
|
+
self._session.mount("http://", adapter)
|
|
359
|
+
self._pool_maxsize = size
|
|
360
|
+
|
|
361
|
+
@staticmethod
|
|
362
|
+
def _create_http_adapter(pool_maxsize: int) -> HTTPAdapter:
|
|
363
|
+
retry = Retry(
|
|
364
|
+
total=3,
|
|
365
|
+
connect=3,
|
|
366
|
+
read=3,
|
|
367
|
+
status=3,
|
|
368
|
+
backoff_factor=0.5,
|
|
369
|
+
status_forcelist=(429, 500, 502, 503, 504),
|
|
370
|
+
allowed_methods=frozenset({"GET"}),
|
|
371
|
+
other=0,
|
|
372
|
+
respect_retry_after_header=True,
|
|
373
|
+
raise_on_status=False,
|
|
374
|
+
)
|
|
375
|
+
return HTTPAdapter(max_retries=retry, pool_maxsize=pool_maxsize)
|
|
376
|
+
|
|
377
|
+
def _get_json(
|
|
378
|
+
self,
|
|
379
|
+
url: str,
|
|
380
|
+
params: Optional[dict],
|
|
381
|
+
token: str,
|
|
382
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
383
|
+
allow_redirects: bool = True,
|
|
384
|
+
) -> Union[dict, requests.Response, List[dict[str, str]], List[str]]:
|
|
385
|
+
if url.startswith("/"):
|
|
386
|
+
url = self.url + url
|
|
387
|
+
|
|
388
|
+
header = {"Authorization": f"Bearer {token}"}
|
|
389
|
+
response = self._session.get(
|
|
390
|
+
url,
|
|
391
|
+
headers=header,
|
|
392
|
+
params=params,
|
|
393
|
+
timeout=timeout,
|
|
394
|
+
allow_redirects=allow_redirects,
|
|
395
|
+
)
|
|
396
|
+
if self.raise_for_status:
|
|
397
|
+
response.raise_for_status()
|
|
398
|
+
|
|
399
|
+
if response.status_code == 200:
|
|
400
|
+
try:
|
|
401
|
+
return response.json()
|
|
402
|
+
except json.JSONDecodeError:
|
|
403
|
+
logger.warning(
|
|
404
|
+
f"Warning: {str(url)} returned successfully, but not with a valid json response"
|
|
405
|
+
)
|
|
406
|
+
else:
|
|
407
|
+
logger.warning(
|
|
408
|
+
f"Warning: {str(url)} returned status code {response.status_code}"
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
return response
|
|
412
|
+
|
|
413
|
+
def get_file(
|
|
414
|
+
self,
|
|
415
|
+
url: str,
|
|
416
|
+
file_name: str,
|
|
417
|
+
stream: bool = True,
|
|
418
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
419
|
+
) -> str:
|
|
420
|
+
"""
|
|
421
|
+
Get file from API endpoint and save it to disk.
|
|
422
|
+
|
|
423
|
+
Args:
|
|
424
|
+
url (str): API endpoint to get file from. Full or partial url to api endpoint. Is prefixed with self.url if url starts with "/".
|
|
425
|
+
file_name (str): Name of file to save to disk, including extension. The file will be saved to the current working directory.
|
|
426
|
+
stream (bool, optional): Set true. Defaults to True.
|
|
427
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
428
|
+
|
|
429
|
+
Raises:
|
|
430
|
+
ValueError: Return error if client authenticator is not set.
|
|
431
|
+
|
|
432
|
+
Returns:
|
|
433
|
+
str: Returns the path to the saved file. Or the context of the downloaded file if no file name is provided.
|
|
434
|
+
"""
|
|
435
|
+
if url.startswith("/"):
|
|
436
|
+
url = self.url + url
|
|
437
|
+
|
|
438
|
+
header = {"Authorization": f"Bearer {self.get_token()}"}
|
|
439
|
+
response = self._session.get(
|
|
440
|
+
url, headers=header, stream=stream, timeout=timeout
|
|
441
|
+
)
|
|
442
|
+
if self.raise_for_status:
|
|
443
|
+
response.raise_for_status()
|
|
444
|
+
|
|
445
|
+
if not (response.status_code == 200):
|
|
446
|
+
logger.warning(
|
|
447
|
+
f"Warning: {str(url)} returned status code {response.status_code}"
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
if file_name is not None and len(file_name) > 0:
|
|
451
|
+
save_path = os.path.join(os.getcwd(), file_name)
|
|
452
|
+
with open(save_path, "wb") as file:
|
|
453
|
+
for chunk in response.iter_content(chunk_size=8192):
|
|
454
|
+
file.write(chunk)
|
|
455
|
+
print(f"File downloaded successfully and saved to {save_path}")
|
|
456
|
+
return save_path
|
|
457
|
+
else:
|
|
458
|
+
return response.text
|
|
459
|
+
# except requests.exceptions.RequestException as e:
|
|
460
|
+
# print(f"Error downloading schema: {e}")
|
|
461
|
+
# except PermissionError as e:
|
|
462
|
+
# print(f"Permission error: {e}")
|
|
463
|
+
# except Exception as e:
|
|
464
|
+
# print(f"An unexpected error occurred: {e}")
|
|
465
|
+
|
|
466
|
+
def post(
|
|
467
|
+
self,
|
|
468
|
+
url: str,
|
|
469
|
+
params: Optional[dict] = None,
|
|
470
|
+
data: Optional[Any] = None,
|
|
471
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
472
|
+
) -> requests.Response:
|
|
473
|
+
"""Post to API endpoint.
|
|
474
|
+
|
|
475
|
+
Args:
|
|
476
|
+
url (str): Url to api endpoint. Is prefixed with self.url if url starts with "/".
|
|
477
|
+
params (Optional[dict], optional): Parameters to pass. Defaults to None.
|
|
478
|
+
data (Optional[Any], optional): Data to post. Defaults to None.
|
|
479
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
480
|
+
|
|
481
|
+
Raises:
|
|
482
|
+
ValueError: Raised if client authenticator is not set.
|
|
483
|
+
|
|
484
|
+
Returns:
|
|
485
|
+
requests.Response: Result returned from API endpoint. Note that the response is not processed in any way, and it is up to the user to handle the response.
|
|
486
|
+
"""
|
|
487
|
+
if url.startswith("/"):
|
|
488
|
+
url = self.url + url
|
|
489
|
+
|
|
490
|
+
header = {"Authorization": f"Bearer {self.get_token()}"}
|
|
491
|
+
response = self._session.post(
|
|
492
|
+
url, headers=header, data=data, params=params, timeout=timeout
|
|
493
|
+
)
|
|
494
|
+
if self.raise_for_status:
|
|
495
|
+
response.raise_for_status()
|
|
496
|
+
|
|
497
|
+
if not (response.status_code == 200):
|
|
498
|
+
logger.warning(
|
|
499
|
+
f"Warning: {str(url)} returned status code {response.status_code}"
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
return response
|
|
503
|
+
|
|
504
|
+
def post_json(
|
|
505
|
+
self,
|
|
506
|
+
url: str,
|
|
507
|
+
upload: Dict[str, List[Dict[str, str]]],
|
|
508
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
509
|
+
) -> requests.Response:
|
|
510
|
+
"""Post JSON to endpoint.
|
|
511
|
+
|
|
512
|
+
Args:
|
|
513
|
+
url (str): API endpoint to post to. Full or partial url to api endpoint. Is prefixed with self.url if url starts with "/".
|
|
514
|
+
upload (Dict[str, List[Dict[str, str]]]): Data to upload. Should be a dictionary where the values are lists of dictionaries with string keys and values.
|
|
515
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
516
|
+
|
|
517
|
+
Raises:
|
|
518
|
+
ValueError: Return error if client authenticator is not set.
|
|
519
|
+
|
|
520
|
+
Returns:
|
|
521
|
+
str: Returns the path to the saved file. Or the context of the downloaded file if no file name is provided.
|
|
522
|
+
"""
|
|
523
|
+
if url.startswith("/"):
|
|
524
|
+
url = self.url + url
|
|
525
|
+
|
|
526
|
+
header = {"Authorization": f"Bearer {self.get_token()}"}
|
|
527
|
+
response = self._session.post(
|
|
528
|
+
url, headers=header, json=upload, timeout=timeout
|
|
529
|
+
)
|
|
530
|
+
if self.raise_for_status:
|
|
531
|
+
response.raise_for_status()
|
|
532
|
+
|
|
533
|
+
if not (response.status_code == 200):
|
|
534
|
+
logger.warning(
|
|
535
|
+
f"Warning: {str(url)} returned status code {response.status_code}"
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
return response
|
|
539
|
+
|
|
540
|
+
def post_file(
|
|
541
|
+
self,
|
|
542
|
+
url: str,
|
|
543
|
+
upload: Dict[str, List[Dict[str, str]]],
|
|
544
|
+
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
|
|
545
|
+
) -> requests.Response:
|
|
546
|
+
"""Post file to API endpoint
|
|
547
|
+
|
|
548
|
+
Args:
|
|
549
|
+
url (str): API endpoint to post to. Full or partial url to api endpoint. Is prefixed with self.url if url starts with "/".
|
|
550
|
+
upload (Dict[str, List[Dict[str, str]]]): Data to upload. Should be a dictionary where the values are lists of dictionaries with string keys and values.
|
|
551
|
+
timeout (Optional[Union[float, Tuple[float, float]]], optional): Request timeout in seconds, or connect/read timeout pair. Defaults to 5 seconds to connect and 60 seconds to read.
|
|
552
|
+
|
|
553
|
+
Raises:
|
|
554
|
+
ValueError: Return error if client authenticator is not set.
|
|
555
|
+
|
|
556
|
+
Returns:
|
|
557
|
+
str: Returns the path to the saved file. Or the context of the downloaded file if no file name is provided.
|
|
558
|
+
"""
|
|
559
|
+
if url.startswith("/"):
|
|
560
|
+
url = self.url + url
|
|
561
|
+
|
|
562
|
+
header = {"Authorization": f"Bearer {self.get_token()}"}
|
|
563
|
+
json_file = BytesIO(json.dumps(upload).encode("utf-8"))
|
|
564
|
+
response = self._session.post(
|
|
565
|
+
url,
|
|
566
|
+
headers=header,
|
|
567
|
+
files={"file": ("upload_data.json", json_file)},
|
|
568
|
+
timeout=timeout,
|
|
569
|
+
)
|
|
570
|
+
if self.raise_for_status:
|
|
571
|
+
response.raise_for_status()
|
|
572
|
+
|
|
573
|
+
if not (response.status_code == 200):
|
|
574
|
+
logger.warning(
|
|
575
|
+
f"Warning: {str(url)} returned status code {response.status_code}"
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
return response
|
|
@@ -166,7 +166,11 @@ class APIConnector(Connector):
|
|
|
166
166
|
scope: Optional[Union[List[str], str]] = None,
|
|
167
167
|
user_name: Optional[str] = None,
|
|
168
168
|
user_assertion: Optional[str] = None,
|
|
169
|
+
<<<<<<< HEAD
|
|
169
170
|
token: Optional[str] = None,
|
|
171
|
+
=======
|
|
172
|
+
subscription_key: Optional[str] = None,
|
|
173
|
+
>>>>>>> a555702 (feat: add support for APIM keys)
|
|
170
174
|
) -> None:
|
|
171
175
|
"""Initialize the API connector.
|
|
172
176
|
|
|
@@ -195,6 +199,7 @@ class APIConnector(Connector):
|
|
|
195
199
|
self._raise_for_status = True
|
|
196
200
|
self._session = requests.Session()
|
|
197
201
|
self._pool_maxsize = DEFAULT_POOLSIZE
|
|
202
|
+
self.subscription_key = subscription_key
|
|
198
203
|
|
|
199
204
|
if user_name is None:
|
|
200
205
|
user_name = f"{get_user_name()}"
|
|
@@ -218,6 +223,20 @@ class APIConnector(Connector):
|
|
|
218
223
|
"""HTTP session shared by all requests, reusing connections between calls."""
|
|
219
224
|
return self._session
|
|
220
225
|
|
|
226
|
+
@property
|
|
227
|
+
def subscription_key(self) -> Optional[str]:
|
|
228
|
+
"""Optional APIM subscription key, sent in addition to the bearer token."""
|
|
229
|
+
return self._session.headers.get("Ocp-Apim-Subscription-Key")
|
|
230
|
+
|
|
231
|
+
@subscription_key.setter
|
|
232
|
+
def subscription_key(self, subscription_key: Optional[str]) -> None:
|
|
233
|
+
if subscription_key is not None and not isinstance(subscription_key, str):
|
|
234
|
+
raise TypeError("Input subscription_key shall be a string or None.")
|
|
235
|
+
if subscription_key:
|
|
236
|
+
self._session.headers["Ocp-Apim-Subscription-Key"] = subscription_key
|
|
237
|
+
else:
|
|
238
|
+
self._session.headers.pop("Ocp-Apim-Subscription-Key", None)
|
|
239
|
+
|
|
221
240
|
@property
|
|
222
241
|
def raise_for_status(self) -> bool:
|
|
223
242
|
return self._raise_for_status
|
eq_api_connector-1.2.2/README.md
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
# eq-api-connector
|
|
2
|
-
A small python package to handle authentication and act as a generic api sdk.
|
|
3
|
-
|
|
4
|
-
It supports apis Public client applications using [acquire_token_interactive](https://learn.microsoft.com/en-us/python/api/msal/msal.application.publicclientapplication?view=msal-py-latest#msal-application-publicclientapplication-acquire-token-interactive) and contains a few basic endpoint accessors.
|
|
5
|
-
|
|
6
|
-
# Install
|
|
7
|
-
Install from pypi ```pip install eq-api-connector``` or clone and use ```uv sync``` as a developer.
|
|
8
|
-
|
|
9
|
-
# Usage
|
|
10
|
-
See the dummy example below
|
|
11
|
-
|
|
12
|
-
```
|
|
13
|
-
from eq_api_connector import APIConnector
|
|
14
|
-
|
|
15
|
-
url_prod = "https://api.gateway.equinor.com/dummy/v1"
|
|
16
|
-
client_id = "insert_your_client_id_here" # IOC SME monitoring SDK
|
|
17
|
-
scope = ["34de7368-10f7-4c34-a4df-928156065f2c/ReadWrite"]
|
|
18
|
-
|
|
19
|
-
c = APIConnector(client_id=client_id, scope=scope)
|
|
20
|
-
c.url_prod = url_prod
|
|
21
|
-
|
|
22
|
-
model_owners = c.get_json("/example-endpoint")
|
|
23
|
-
````
|
|
24
|
-
|
|
25
|
-
If you already have an access token, pass it with `token`:
|
|
26
|
-
|
|
27
|
-
```
|
|
28
|
-
access_token = get_access_token_from_your_auth_flow()
|
|
29
|
-
c = APIConnector(token=access_token)
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
When a token is supplied, `APIConnector` uses it as-is and does not check its expiry or refresh it. The caller is responsible for obtaining and supplying a fresh token when it expires.
|
|
33
|
-
|
|
34
|
-
Typically packages using eq-api-connector should subclass the APIConnector or keep a singleton a reference.
|
|
35
|
-
|
|
File without changes
|