eq-api-connector 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Equinor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.3
2
+ Name: eq-api-connector
3
+ Version: 0.1.0
4
+ Summary: Equinor API connector (API SDK) to connect to public client app registrations.
5
+ License: MIT
6
+ Author: Åsmund Våge Fannemel
7
+ Author-email: asmf@equinor.com
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: azure-identity (>=1.24.0,<2.0.0)
16
+ Requires-Dist: msal-bearer (>=1.3.3,<2.0.0)
17
+ Requires-Dist: requests (>=2.32.5,<3.0.0)
18
+ Description-Content-Type: text/markdown
19
+
20
+ # public-api-connector
21
+ API connector (API SDK) to connect to public client app registrations.
@@ -0,0 +1,2 @@
1
+ # public-api-connector
2
+ API connector (API SDK) to connect to public client app registrations.
@@ -0,0 +1,27 @@
1
+ import logging
2
+
3
+ from connector_api import (
4
+ set_tenant,
5
+ set_public_client_id,
6
+ set_scope,
7
+ set_url_prod,
8
+ set_url_dev,
9
+ get_app_token,
10
+ get_json,
11
+ get_api_url,
12
+ post_json,
13
+ )
14
+
15
+ __all__ = [
16
+ "set_tenant",
17
+ "set_public_client_id",
18
+ "set_scope",
19
+ "set_url_prod",
20
+ "set_url_dev",
21
+ "get_app_token",
22
+ "get_json",
23
+ "get_api_url",
24
+ "post_json",
25
+ ]
26
+
27
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -0,0 +1,280 @@
1
+ import json
2
+ import logging
3
+ from types import SimpleNamespace
4
+ from typing import Dict, List, Optional, Union
5
+ from azure.identity import DefaultAzureCredential
6
+ import requests
7
+ from msal_bearer import BearerAuth, get_user_name
8
+ from io import BytesIO
9
+ import os
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # MSAL-settings
15
+ _tenantID = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0" # Equinor tenant
16
+ _public_client_id = ""
17
+ _scope = []
18
+
19
+
20
+ _token = ""
21
+ _user_name = ""
22
+
23
+ _raise_for_status = True
24
+
25
+ _use_dev = False
26
+ _url_prod = ""
27
+ _url_dev = ""
28
+
29
+
30
+ def set_tenant(tenant_id: str) -> None:
31
+ """Setter for global property _tenantID.
32
+
33
+ Args:
34
+ tenant_id (str): Tenant ID to set.
35
+ """
36
+ global _tenantID
37
+ _tenantID = tenant_id
38
+
39
+
40
+ def set_public_client_id(client_id: str) -> None:
41
+ """Setter for global property _public_client_id.
42
+
43
+ Args:
44
+ client_id (str): Client ID to set.
45
+ """
46
+ global _public_client_id
47
+ _public_client_id = client_id
48
+
49
+
50
+ def set_scope(scope: List[str]) -> None:
51
+ """Setter for global property _scope.
52
+
53
+ Args:
54
+ scope (str): Scope to set.
55
+ """
56
+ global _scope
57
+ _scope = scope
58
+
59
+
60
+ def set_url_prod(url: str) -> None:
61
+ """Setter for global property _url_prod.
62
+
63
+ Args:
64
+ url (str): URL to set.
65
+ """
66
+ global _url_prod
67
+ _url_prod = url
68
+
69
+
70
+ def set_url_dev(url: str) -> None:
71
+ """Setter for global property _url_dev.
72
+
73
+ Args:
74
+ url (str): URL to set.
75
+ """
76
+ global _url_dev
77
+ _url_dev = url
78
+
79
+
80
+ def set_token(token: str) -> None:
81
+ """Setter for global property token.
82
+
83
+ Args:
84
+ token (str): Token to set.
85
+ """
86
+ global _token
87
+ _token = token
88
+
89
+
90
+ def get_token() -> str:
91
+ """Getter for token. Will first see if a global token has been set, then try to get a token using app registration, then last try to get via azure authentication.
92
+
93
+ Returns:
94
+ str: Authentication token
95
+ """
96
+ if _token:
97
+
98
+ return _token
99
+
100
+ token = get_app_token()
101
+
102
+ if token:
103
+ return token
104
+
105
+ return get_az_token()
106
+
107
+
108
+ def get_az_token() -> str:
109
+ """Getter for token uzing azure authentication.
110
+
111
+ Returns:
112
+ str: Token from azure authentication
113
+ """
114
+ credential = DefaultAzureCredential()
115
+ databaseToken = credential.get_token(_public_client_id)
116
+ return databaseToken[0]
117
+
118
+
119
+ def get_app_bearer(username: str = "") -> str:
120
+ global _user_name
121
+
122
+ if not username:
123
+ if not _user_name:
124
+ _user_name = get_user_name()
125
+ username = _user_name # type: ignore
126
+ else:
127
+ _user_name = username
128
+
129
+ # SHORTNAME@equinor.com -- short name shall be capitalized
130
+ if not username.endswith("@EQUINOR.COM"):
131
+ username = username + "@EQUINOR.COM"
132
+ username = username.upper() # Also capitalize equinor.com
133
+
134
+ auth = BearerAuth.get_auth(
135
+ tenantID=_tenantID,
136
+ clientID=_public_client_id,
137
+ scopes=_scope,
138
+ username=username,
139
+ token_location="api_token_cache.bin",
140
+ )
141
+ return auth.token # type: ignore
142
+
143
+
144
+ def get_app_token(username: str = "") -> str:
145
+ """Getter for token using app registration authentication.
146
+
147
+ Args:
148
+ username (str, optional): User name (email address) of user to get token for.
149
+
150
+ Returns:
151
+ str: Token from app registration
152
+ """
153
+ return get_app_bearer(username=username)
154
+
155
+
156
+ def get_object_from_json(text: str):
157
+ if isinstance(text, list):
158
+ obj = [json.loads(x, object_hook=lambda d: SimpleNamespace(**d)) for x in text]
159
+ else:
160
+ obj = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
161
+ return obj
162
+
163
+
164
+ def set_use_dev(use_dev: bool):
165
+ """Setter for global property _use_dev.
166
+ If _use_dev is True, the API URL will be set to the development URL,
167
+ otherwise it will be set to the production URL.
168
+
169
+ Args:
170
+ use_dev (bool): Value to set _use_dev to.
171
+
172
+ Raises:
173
+ TypeError: In case input use_dev is not a boolean.
174
+ """
175
+ global _use_dev
176
+
177
+ if not isinstance(use_dev, bool):
178
+ raise TypeError("Input use_dev shall be boolean.")
179
+
180
+ _use_dev = use_dev
181
+
182
+
183
+ def set_raise_for_status(raise_for_status: bool):
184
+ """Setter for global property _raise_for_status.
185
+ If _raise_for_status is True, the requests will raise an exception for HTTP errors,
186
+ otherwise it will not.
187
+
188
+ Args:
189
+ raise_for_status (bool): Value to set _raise_for_status to.
190
+
191
+ Raises:
192
+ TypeError: In case input raise_for_status is not a boolean.
193
+ """
194
+ global _raise_for_status
195
+
196
+ if not isinstance(raise_for_status, bool):
197
+ raise TypeError("Input raise_for_status shall be boolean.")
198
+
199
+ _raise_for_status = raise_for_status
200
+
201
+
202
+ def get_api_url() -> str:
203
+ """Getter for API URL. Will return the dev URL if _use_dev is True, otherwise will return the production URL.
204
+ Returns:
205
+ str: API URL
206
+ """
207
+ if _use_dev:
208
+ return _url_dev
209
+ else:
210
+ return _url_prod
211
+
212
+
213
+ def get_json(url: str, params: Optional[dict] = None) -> Union[dict, requests.Response]:
214
+ token = get_token()
215
+ header = {"Authorization": f"Bearer {token}"}
216
+ response = requests.get(url, headers=header, params=params)
217
+ if _raise_for_status:
218
+ response.raise_for_status()
219
+
220
+ if response.status_code == 200:
221
+ try:
222
+ return response.json()
223
+ except json.JSONDecodeError:
224
+ logger.warning(
225
+ f"Warning: {str(url)} returned successfully, but not with a valid json response"
226
+ )
227
+ else:
228
+ logger.warning(
229
+ f"Warning: {str(url)} returned status code {response.status_code}"
230
+ )
231
+
232
+ return response
233
+
234
+
235
+ def get_file(url: str, file_name: str, stream=True) -> str:
236
+ token = get_token()
237
+ header = {"Authorization": f"Bearer {token}"}
238
+ response = requests.get(url, headers=header, stream=stream)
239
+ # try:
240
+ if _raise_for_status:
241
+ response.raise_for_status()
242
+
243
+ if not (response.status_code == 200):
244
+ logger.warning(
245
+ f"Warning: {str(url)} returned status code {response.status_code}"
246
+ )
247
+
248
+ if file_name is not None and len(file_name) > 0:
249
+ save_path = os.path.join(os.getcwd(), file_name)
250
+ with open(save_path, "wb") as file:
251
+ for chunk in response.iter_content(chunk_size=8192):
252
+ file.write(chunk)
253
+ print(f"File downloaded successfully and saved to {save_path}")
254
+ return save_path
255
+ else:
256
+ return response.text
257
+ # except requests.exceptions.RequestException as e:
258
+ # print(f"Error downloading schema: {e}")
259
+ # except PermissionError as e:
260
+ # print(f"Permission error: {e}")
261
+ # except Exception as e:
262
+ # print(f"An unexpected error occurred: {e}")
263
+
264
+
265
+ def post_json(url: str, upload: Dict[str, List[Dict[str, str]]]):
266
+ header = {"Authorization": f"Bearer {get_token()}"}
267
+ json_file = BytesIO(json.dumps(upload).encode("utf-8"))
268
+ response = requests.post(
269
+ url, headers=header, files={"file": ("upload_data.json", json_file)}
270
+ )
271
+
272
+ if _raise_for_status:
273
+ response.raise_for_status()
274
+
275
+ if not (response.status_code == 200):
276
+ logger.warning(
277
+ f"Warning: {str(url)} returned status code {response.status_code}"
278
+ )
279
+
280
+ return response
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "eq-api-connector"
3
+ version = "0.1.0"
4
+ description = "Equinor API connector (API SDK) to connect to public client app registrations."
5
+ authors = [
6
+ {name = "Åsmund Våge Fannemel",email = "asmf@equinor.com"}
7
+ ]
8
+ license = {text = "MIT"}
9
+ readme = "README.md"
10
+ requires-python = ">=3.10,<4.0"
11
+ dependencies = [
12
+ "msal-bearer (>=1.3.3,<2.0.0)",
13
+ "requests (>=2.32.5,<3.0.0)",
14
+ "azure-identity (>=1.24.0,<2.0.0)"
15
+ ]
16
+
17
+ [tool.poetry]
18
+
19
+ [tool.poetry.group.test.dependencies]
20
+ pytest = "^7.4.0"
21
+ pytest-cov = "^4.1.0"
22
+
23
+ [tool.poetry.group.dev.dependencies]
24
+ black = "^25.1.0"
25
+
26
+ [build-system]
27
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
28
+ build-backend = "poetry.core.masonry.api"