brreg-wrapper 0.1.0__py3-none-any.whl

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,4 @@
1
+ # src/brreg_wrapper/__init__.py
2
+ from .client import BrregClient
3
+
4
+ __all__ = ["BrregClient"]
@@ -0,0 +1,333 @@
1
+ import httpx
2
+
3
+
4
+ class BrregClient:
5
+ """
6
+ A client for interacting with the Brønnøysund Register Centre (Brreg) API.
7
+ API Documentation: https://data.brreg.no/enhetsregisteret/api/dokumentasjon/no/index.html
8
+ """
9
+
10
+ BASE_URL = "https://data.brreg.no/enhetsregisteret/api"
11
+
12
+ def __init__(self, timeout: float = 10.0, client: httpx.AsyncClient | None = None):
13
+ """
14
+ Initializes the BrregClient.
15
+
16
+ Args:
17
+ timeout: The timeout for HTTP requests in seconds. Defaults to 10.0.
18
+ client: An optional httpx.AsyncClient instance. If not provided,
19
+ a new one is created.
20
+ """
21
+ self._client = client or httpx.AsyncClient(
22
+ base_url=self.BASE_URL, timeout=timeout
23
+ )
24
+
25
+ async def _request(
26
+ self,
27
+ method: str,
28
+ endpoint: str,
29
+ params: dict | None = None,
30
+ json: dict | None = None,
31
+ ) -> httpx.Response:
32
+ """
33
+ Makes an asynchronous HTTP request to the Brreg API.
34
+
35
+ Args:
36
+ method: The HTTP method (e.g., "GET", "POST").
37
+ endpoint: The API endpoint path (e.g., "/enheter").
38
+ params: Optional query parameters.
39
+ json: Optional JSON body for POST/PUT requests.
40
+
41
+ Returns:
42
+ The httpx.Response object.
43
+
44
+ Raises:
45
+ httpx.HTTPStatusError: If the API returns an error status code.
46
+ """
47
+ headers = {"Accept": "application/json"}
48
+ try:
49
+ response = await self._client.request(
50
+ method, endpoint, params=params, json=json, headers=headers
51
+ )
52
+ # Raise an exception for 4xx or 5xx status codes
53
+ response.raise_for_status()
54
+ return response
55
+ except httpx.RequestError as exc:
56
+ print(f"An error occurred while requesting {exc.request.url!r}: {exc}")
57
+ # Re-raise or handle specific errors as needed
58
+ raise
59
+ except httpx.HTTPStatusError as exc:
60
+ error_message = (
61
+ f"Error response {exc.response.status_code} "
62
+ f"while requesting {exc.request.url!r}: {exc.response.text}"
63
+ )
64
+ print(error_message)
65
+ # Re-raise or handle specific errors as needed
66
+ raise
67
+
68
+ async def close(self):
69
+ """Closes the underlying httpx client."""
70
+ await self._client.aclose()
71
+
72
+ # --- API Methods will be added below ---
73
+
74
+ async def get_enhet(self, organisasjonsnummer: str) -> dict:
75
+ """
76
+ Retrieves information about a specific entity (enhet) by its
77
+ organization number.
78
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-enheter-detalj
79
+
80
+ Args:
81
+ organisasjonsnummer: The 9-digit organization number.
82
+
83
+ Returns:
84
+ A dictionary containing the entity's information.
85
+ """
86
+ endpoint = f"/enheter/{organisasjonsnummer}"
87
+ response = await self._request("GET", endpoint)
88
+ return response.json()
89
+
90
+ async def search_enheter(self, **kwargs) -> dict:
91
+ """
92
+ Searches for entities (enheter) based on various criteria.
93
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-enheter-oppslag
94
+
95
+ Args:
96
+ **kwargs: Search parameters as defined in the API documentation.
97
+ Examples: navn, organisasjonsform, postadresse.postnummer, etc.
98
+
99
+ Returns:
100
+ A dictionary containing the search results.
101
+ """
102
+ endpoint = "/enheter"
103
+ # Filter out None values from kwargs
104
+ params = {k: v for k, v in kwargs.items() if v is not None}
105
+ response = await self._request("GET", endpoint, params=params)
106
+ return response.json()
107
+
108
+ async def get_underenhet(self, organisasjonsnummer: str) -> dict:
109
+ """
110
+ Retrieves information about a specific sub-entity (underenhet) by its
111
+ organization number.
112
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-underenheter-detalj
113
+
114
+ Args:
115
+ organisasjonsnummer: The 9-digit organization number of the sub-entity.
116
+
117
+ Returns:
118
+ A dictionary containing the sub-entity's information.
119
+ """
120
+ endpoint = f"/underenheter/{organisasjonsnummer}"
121
+ response = await self._request("GET", endpoint)
122
+ return response.json()
123
+
124
+ async def search_underenheter(self, **kwargs) -> dict:
125
+ """
126
+ Searches for sub-entities (underenheter) based on various criteria.
127
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-underenheter-oppslag
128
+
129
+ Args:
130
+ **kwargs: Search parameters as defined in the API documentation.
131
+
132
+ Returns:
133
+ A dictionary containing the search results.
134
+ """
135
+ endpoint = "/underenheter"
136
+ # Filter out None values from kwargs
137
+ params = {k: v for k, v in kwargs.items() if v is not None}
138
+ response = await self._request("GET", endpoint, params=params)
139
+ return response.json()
140
+
141
+ # --- Roles Endpoints ---
142
+
143
+ async def get_rollegrupper(self) -> dict:
144
+ """
145
+ Retrieves all role groups.
146
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-roller-rollegrupper
147
+
148
+ Returns:
149
+ A dictionary containing the list of role groups.
150
+ """
151
+ endpoint = "/roller/rollegrupper"
152
+ response = await self._request("GET", endpoint)
153
+ return response.json()
154
+
155
+ async def get_roller(self) -> dict:
156
+ """
157
+ Retrieves all roles.
158
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-roller-roller
159
+
160
+ Returns:
161
+ A dictionary containing the list of roles.
162
+ """
163
+ endpoint = "/roller/roller"
164
+ response = await self._request("GET", endpoint)
165
+ return response.json()
166
+
167
+ async def get_enhet_roller(self, organisasjonsnummer: str) -> dict:
168
+ """
169
+ Retrieves roles associated with a specific entity (enhet).
170
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-roller-roller-for-enhet
171
+
172
+ Args:
173
+ organisasjonsnummer: The 9-digit organization number of the entity.
174
+
175
+ Returns:
176
+ A dictionary containing the roles for the entity.
177
+ """
178
+ endpoint = f"/enheter/{organisasjonsnummer}/roller"
179
+ response = await self._request("GET", endpoint)
180
+ return response.json()
181
+
182
+ async def get_underenhet_roller(self, organisasjonsnummer: str) -> dict:
183
+ """
184
+ Retrieves roles associated with a specific sub-entity (underenhet).
185
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-roller-roller-for-underenhet
186
+
187
+ Args:
188
+ organisasjonsnummer: The 9-digit organization number of the sub-entity.
189
+
190
+ Returns:
191
+ A dictionary containing the roles for the sub-entity.
192
+ """
193
+ endpoint = f"/underenheter/{organisasjonsnummer}/roller"
194
+ response = await self._request("GET", endpoint)
195
+ return response.json()
196
+
197
+ # --- Grunndata Endpoints ---
198
+
199
+ async def get_grunndata_enhet(self, organisasjonsnummer: str) -> dict:
200
+ """
201
+ Retrieves basic data (grunndata) for a specific entity (enhet).
202
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-grunndata-enhet
203
+
204
+ Args:
205
+ organisasjonsnummer: The 9-digit organization number of the entity.
206
+
207
+ Returns:
208
+ A dictionary containing the basic data for the entity.
209
+ """
210
+ endpoint = f"/grunndata/enheter/{organisasjonsnummer}"
211
+ response = await self._request("GET", endpoint)
212
+ return response.json()
213
+
214
+ async def get_grunndata_underenhet(self, organisasjonsnummer: str) -> dict:
215
+ """
216
+ Retrieves basic data (grunndata) for a specific sub-entity (underenhet).
217
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-grunndata-underenhet
218
+
219
+ Args:
220
+ organisasjonsnummer: The 9-digit organization number of the sub-entity.
221
+
222
+ Returns:
223
+ A dictionary containing the basic data for the sub-entity.
224
+ """
225
+ endpoint = f"/grunndata/underenheter/{organisasjonsnummer}"
226
+ response = await self._request("GET", endpoint)
227
+ return response.json()
228
+
229
+ # --- Code List Endpoints ---
230
+
231
+ async def get_organisasjonsformer(self) -> dict:
232
+ """
233
+ Retrieves all organization forms.
234
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-kodeverk-organisasjonsformer
235
+
236
+ Returns:
237
+ A dictionary containing the list of organization forms.
238
+ """
239
+ endpoint = "/organisasjonsformer"
240
+ response = await self._request("GET", endpoint)
241
+ return response.json()
242
+
243
+ async def get_naeringskoder(self) -> dict:
244
+ """
245
+ Retrieves all industry codes (Næringskoder - NACE).
246
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-kodeverk-naeringskoder
247
+
248
+ Returns:
249
+ A dictionary containing the list of industry codes.
250
+ """
251
+ endpoint = "/naeringskoder"
252
+ response = await self._request("GET", endpoint)
253
+ return response.json()
254
+
255
+ async def get_sektorkoder(self) -> dict:
256
+ """
257
+ Retrieves all sector codes.
258
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-kodeverk-sektorkoder
259
+
260
+ Returns:
261
+ A dictionary containing the list of sector codes.
262
+ """
263
+ endpoint = "/sektorkoder"
264
+ response = await self._request("GET", endpoint)
265
+ return response.json()
266
+
267
+ # --- Update Endpoints ---
268
+
269
+ async def get_enhet_oppdateringer(self, **kwargs) -> dict:
270
+ """
271
+ Retrieves updates for entities (enheter).
272
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-oppdateringer-enheter
273
+
274
+ Args:
275
+ **kwargs: Optional query parameters like oppdateringsid, dato,
276
+ fraAntallDoegn, status, oppdateringstype, page, size.
277
+
278
+ Returns:
279
+ A dictionary containing the entity updates.
280
+ """
281
+ endpoint = "/oppdateringer/enheter"
282
+ params = {k: v for k, v in kwargs.items() if v is not None}
283
+ response = await self._request("GET", endpoint, params=params)
284
+ return response.json()
285
+
286
+ async def get_underenhet_oppdateringer(self, **kwargs) -> dict:
287
+ """
288
+ Retrieves updates for sub-entities (underenheter).
289
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-oppdateringer-underenheter
290
+
291
+ Args:
292
+ **kwargs: Optional query parameters like oppdateringsid, dato,
293
+ fraAntallDoegn, status, oppdateringstype, page, size.
294
+
295
+ Returns:
296
+ A dictionary containing the sub-entity updates.
297
+ """
298
+ endpoint = "/oppdateringer/underenheter"
299
+ params = {k: v for k, v in kwargs.items() if v is not None}
300
+ response = await self._request("GET", endpoint, params=params)
301
+ return response.json()
302
+
303
+ # --- History Endpoints ---
304
+
305
+ async def get_enhet_historikk(self, organisasjonsnummer: str) -> dict:
306
+ """
307
+ Retrieves historical data for a specific entity (enhet).
308
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-historikk-enhet
309
+
310
+ Args:
311
+ organisasjonsnummer: The 9-digit organization number of the entity.
312
+
313
+ Returns:
314
+ A dictionary containing the historical data for the entity.
315
+ """
316
+ endpoint = f"/enheter/{organisasjonsnummer}/historikk"
317
+ response = await self._request("GET", endpoint)
318
+ return response.json()
319
+
320
+ async def get_underenhet_historikk(self, organisasjonsnummer: str) -> dict:
321
+ """
322
+ Retrieves historical data for a specific sub-entity (underenhet).
323
+ Ref: https://data.brreg.no/enhetsregisteret/api/docs/index.html#rest-api-historikk-underenhet
324
+
325
+ Args:
326
+ organisasjonsnummer: The 9-digit organization number of the sub-entity.
327
+
328
+ Returns:
329
+ A dictionary containing the historical data for the sub-entity.
330
+ """
331
+ endpoint = f"/underenheter/{organisasjonsnummer}/historikk"
332
+ response = await self._request("GET", endpoint)
333
+ return response.json()
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: brreg-wrapper
3
+ Version: 0.1.0
4
+ Summary: A Python wrapper for the Brønnøysund Register Centre (Brreg) API.
5
+ Author-email: Sondre Dyrnes <sondre@villdyr.no>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sondreal/brreg-wrapper
8
+ Project-URL: Repository, https://github.com/sondreal/brreg-wrapper
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Topic :: Office/Business
16
+ Requires-Python: >=3.13
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx<1.0,>=0.27
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest<9.0,>=8.0; extra == "dev"
22
+ Requires-Dist: pytest-asyncio<1.0,>=0.23; extra == "dev"
23
+ Requires-Dist: pytest-httpx<1.0,>=0.29; extra == "dev"
24
+ Requires-Dist: ruff<1.0,>=0.3; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # 🔥 Brreg Wrapper
28
+
29
+ [![PyPI version](https://img.shields.io/pypi/v/brreg-wrapper.svg)](https://pypi.org/project/brreg-wrapper/)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+ [![Python Version](https://img.shields.io/pypi/pyversions/brreg-wrapper.svg)](https://pypi.org/project/brreg-wrapper/)
32
+
33
+ <!-- Optional: Add build status badge if you set up CI beyond publishing -->
34
+ <!-- [![Build Status](https://github.com/sondreal/brreg-wrapper/actions/workflows/your-ci-workflow.yml/badge.svg)](https://github.com/sondreal/brreg-wrapper/actions/workflows/your-ci-workflow.yml) -->
35
+
36
+ Tired of wrestling with raw API calls to the Brønnøysund Register Centre (Brreg)? **`brreg-wrapper`** is here to simplify your life! This sleek, asynchronous Python library provides an intuitive interface to access crucial Norwegian business information with ease.
37
+
38
+ Get details on main entities (`enheter`) and sub-entities (`underenheter`), perform searches, and integrate Norwegian business data into your applications effortlessly.
39
+
40
+ ## ✨ Features
41
+
42
+ - **Asynchronous:** Built with `asyncio` and `httpx` for modern, non-blocking I/O.
43
+ - **Simple Interface:** Clean methods like `get_enhet`, `get_underenhet`, `search_enheter`, `search_underenheter`.
44
+ - **Type Hinted:** Fully type-hinted for better developer experience and static analysis.
45
+ - **Minimal Dependencies:** Relies only on the excellent `httpx` library.
46
+ - **PyPI Ready:** Easy to install and integrate.
47
+
48
+ ## 🚀 Installation
49
+
50
+ Get started in seconds:
51
+
52
+ ```bash
53
+ pip install brreg-wrapper
54
+ # Or using uv:
55
+ # uv pip install brreg-wrapper
56
+ ```
57
+
58
+ ## 💡 Usage Example
59
+
60
+ Here's a taste of how easy it is to fetch data:
61
+
62
+ ```python
63
+ import asyncio
64
+ import json
65
+ from brreg_wrapper import BrregClient
66
+
67
+ async def main():
68
+ # The client automatically handles HTTP sessions
69
+ async with BrregClient() as client:
70
+ org_nr = "982038576" # Example: Google Norway AS
71
+
72
+ print(f"🔍 Fetching details for organization number: {org_nr}")
73
+ try:
74
+ entity_info = await client.get_enhet(org_nr)
75
+ print("\n--- Entity Details ---")
76
+ # Pretty print the JSON response
77
+ print(json.dumps(entity_info, indent=2, ensure_ascii=False))
78
+
79
+ # Want to find sub-entities?
80
+ # sub_entity_info = await client.get_underenhet("some_sub_org_nr")
81
+ # print(json.dumps(sub_entity_info, indent=2, ensure_ascii=False))
82
+
83
+ except Exception as e:
84
+ print(f"\n💥 Oops! An error occurred: {e}")
85
+
86
+ print("\n✅ Done!")
87
+
88
+ if __name__ == "__main__":
89
+ asyncio.run(main())
90
+ ```
91
+
92
+ ## 🤝 Contributing
93
+
94
+ Contributions are welcome! If you have ideas for improvements or find a bug, please open an issue or submit a pull request on the [GitHub repository](https://github.com/sondreal/brreg-wrapper).
95
+
96
+ ## 📜 License
97
+
98
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. Remember to replace `[year]` and `[fullname]` in the file!
99
+
100
+ ## ⚠️ Issues?
101
+
102
+ Having trouble? Found a bug? Feel free to open an issue on the [GitHub repository](https://github.com/sondreal/brreg-wrapper/issues).
@@ -0,0 +1,7 @@
1
+ brreg_wrapper/__init__.py,sha256=J8HOyoxvoUAq4a6CtrcVr5O5m9q6cfUaViuHQDWVZuY,91
2
+ brreg_wrapper/client.py,sha256=Ir5W4GLz3I5B8iWPYqdtFGpMfrbFLLnZuiA2DxwgADw,12445
3
+ brreg_wrapper-0.1.0.dist-info/licenses/LICENSE,sha256=ACwmltkrXIz5VsEQcrqljq-fat6ZXAMepjXGoe40KtE,1069
4
+ brreg_wrapper-0.1.0.dist-info/METADATA,sha256=Rww9A-nQ5HQIWy3mrSOri-trcrpd8_5qqpN6LP1_Dp8,4228
5
+ brreg_wrapper-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
6
+ brreg_wrapper-0.1.0.dist-info/top_level.txt,sha256=DCKBna9al_TqtzSfYTV7Mrl9f6NTRYMC3aavlSqicMY,14
7
+ brreg_wrapper-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [year] [fullname]
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 @@
1
+ brreg_wrapper