A Python wrapper for the Brønnøysund Register Centre (Brreg) API.
Project description
🔥 Brreg Wrapper
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.
Get details on main entities (enheter) and sub-entities (underenheter), perform searches, and integrate Norwegian business data into your applications effortlessly.
✨ Core Features
- Asynchronous: Built with
asyncioandhttpxfor modern, non-blocking I/O. - Type Hinted: Fully type-hinted for better developer experience and static analysis.
- Pydantic Models: Uses Pydantic models for robust data validation and easy object access.
- Context Management: Supports
async withfor automatic HTTP client cleanup. - Comprehensive API Coverage: Wraps numerous endpoints from the official Brreg API.
- Advanced Features:
- Error Handling: Custom exception types for different API errors.
- Caching: Built-in response caching for frequent requests.
- Retry Logic: Automatic retries for transient failures.
- Rate Limiting: Configurable rate limiting to stay within API constraints.
- Batch Operations: Efficiently fetch multiple items in parallel.
- Minimal Dependencies: Relies primarily on
httpx,pydantic, andtenacity.
🚀 Installation
Get started in seconds:
pip install brreg-wrapper
# Or using uv (recommended for speed):
uv pip install brreg-wrapper
# For HTTP/2 support:
pip install brreg-wrapper[http2]
# Or with uv:
uv pip install "brreg-wrapper[http2]"
💡 Basic Usage
import asyncio
import json
from brreg_wrapper import BrregClient
async def main():
# The client automatically handles HTTP sessions
async with BrregClient() as client:
org_nr = "923609016" # Example: Equinor ASA
print(f"🔍 Fetching details for organization number: {org_nr}")
try:
# get_enhet returns a Pydantic model (Enhet or SlettetEnhet)
entity_model = await client.get_enhet(org_nr)
print("\n--- Entity Details (as Pydantic Model) ---")
print(entity_model) # You can work with the model object directly
# To serialize to JSON, convert the model to a JSON-compatible dictionary first
# using mode='json'. This handles types like dates correctly.
print("\n--- Entity Details (as JSON) ---")
entity_dict = entity_model.model_dump(mode='json', by_alias=True, exclude_none=True)
print(json.dumps(entity_dict, indent=2, ensure_ascii=False))
except Exception as e:
print(f"\n💥 Oops! An error occurred: {e}")
print("\n✅ Done!")
if __name__ == "__main__":
asyncio.run(main())
🚀 Advanced Features
Caching & Rate Limiting
from datetime import timedelta
from brreg_wrapper import BrregClient
async def main():
# Enable caching with 1-hour TTL and rate limiting (1 request per second)
client = BrregClient(
cache_ttl=timedelta(hours=1),
rate_limit=1.0 # seconds between requests
)
# First request fetches from API
entity1 = await client.get_enhet("923609016")
# Second request uses cache
entity2 = await client.get_enhet("923609016")
# Clear specific cache entries
client.clear_cache(pattern="enhet_")
# Get cache statistics
cache_info = client.get_cache_info()
print(f"Cache entries: {cache_info['count']}")
Error Handling & Retry Logic
from brreg_wrapper import BrregClient, BrregAPIError, BrregRateLimitError
async def main():
# Configure with automatic retries for transient errors
client = BrregClient(max_retries=3)
try:
entity = await client.get_enhet("invalid_org_nr") # Will raise exception
except BrregRateLimitError:
# Handle rate limit specifically
print("Rate limit exceeded, try again later")
except BrregAPIError as e:
# Handle all API-related errors
print(f"API error: {e} (status code: {e.status_code})")
Batch Operations
from brreg_wrapper import BrregClient
async def main():
client = BrregClient()
# Fetch multiple entities in parallel
org_numbers = ["923609016", "998463718", "913492978"]
results = await client.get_multiple_enheter(org_numbers)
for org_nr, entity in results.items():
if isinstance(entity, Exception):
print(f"Error fetching {org_nr}: {entity}")
else:
print(f"{org_nr}: {entity.navn}")
📂 Project Structure
src/brreg_wrapper: Main package source codeclient.py: The API client implementationexceptions.py: Custom exception classesmodels/: Pydantic models for API responses
examples/: Example scripts showing how to use the packagesample.py: Comprehensive example demonstrating key features
scripts/: Development utility scriptstest_install.sh&test_install.bat: Scripts to test installation
tests/: Unit and integration tests
🧪 Testing
We use pytest for testing. To run the tests:
# Using pip
pip install -e ".[dev]"
pytest
# Using UV (recommended)
uv pip install -e ".[dev]"
pytest
To test the package installation locally before publishing:
# On Unix/Linux/macOS
chmod +x scripts/test_install.sh
./scripts/test_install.sh
# On Windows
scripts\test_install.bat
🤝 Contributing
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.
📜 License
This project is licensed under the MIT License - see the LICENSE file for details.
⚠️ Issues?
Having trouble? Found a bug? Feel free to open an issue on the GitHub repository.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file brreg_wrapper-0.2.1.tar.gz.
File metadata
- Download URL: brreg_wrapper-0.2.1.tar.gz
- Upload date:
- Size: 30.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
036987415251a32e651f97b78d007c7f3820d8cbab48137f09764abf75958d00
|
|
| MD5 |
f2cc0a4ea2c7425cf94e74f487bce933
|
|
| BLAKE2b-256 |
a4a7dc6e24fcb2432cffe3034e25eb64762600078c0317f64c934b94c7e9ab35
|
Provenance
The following attestation bundles were made for brreg_wrapper-0.2.1.tar.gz:
Publisher:
publish-to-pypi.yml on sondreal/brreg-wrapper
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
brreg_wrapper-0.2.1.tar.gz -
Subject digest:
036987415251a32e651f97b78d007c7f3820d8cbab48137f09764abf75958d00 - Sigstore transparency entry: 1437398357
- Sigstore integration time:
-
Permalink:
sondreal/brreg-wrapper@889f7aaf779ec493ac5b1d19bc906e658f9a38de -
Branch / Tag:
refs/tags/v0.2.1 - Owner: https://github.com/sondreal
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@889f7aaf779ec493ac5b1d19bc906e658f9a38de -
Trigger Event:
release
-
Statement type:
File details
Details for the file brreg_wrapper-0.2.1-py3-none-any.whl.
File metadata
- Download URL: brreg_wrapper-0.2.1-py3-none-any.whl
- Upload date:
- Size: 22.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
85001ac3d0b1eb2204d0bb9d579bbbe97842f99217c93903aea9a99b6876f238
|
|
| MD5 |
3b6b86c053076ddd9aaf4c850539757a
|
|
| BLAKE2b-256 |
b481c5992fce70956b8ea9cf80c15128de1a6cf1aa0b066747162aa20e3d0bef
|
Provenance
The following attestation bundles were made for brreg_wrapper-0.2.1-py3-none-any.whl:
Publisher:
publish-to-pypi.yml on sondreal/brreg-wrapper
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
brreg_wrapper-0.2.1-py3-none-any.whl -
Subject digest:
85001ac3d0b1eb2204d0bb9d579bbbe97842f99217c93903aea9a99b6876f238 - Sigstore transparency entry: 1437398360
- Sigstore integration time:
-
Permalink:
sondreal/brreg-wrapper@889f7aaf779ec493ac5b1d19bc906e658f9a38de -
Branch / Tag:
refs/tags/v0.2.1 - Owner: https://github.com/sondreal
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@889f7aaf779ec493ac5b1d19bc906e658f9a38de -
Trigger Event:
release
-
Statement type: