Skip to main content

🔥 Brreg Wrapper

PyPI version License: MIT Python Version

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 asyncio and httpx for 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 with for 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, and tenacity.

🚀 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 (keys are request paths + query string)
    client.clear_cache(pattern="/enheter/923609016")
    
    # Get cache statistics
    cache_info = client.get_cache_info()
    print(f"Cache entries: {cache_info['count']}")

Error Handling & Retry Logic

from brreg_wrapper import (
    BrregAPIError,
    BrregClient,
    BrregRateLimitError,
    BrregResourceNotFoundError,
)

async def main():
    # Transient errors (5xx, 429, timeouts, connection errors) are retried
    # with exponential backoff, honouring the server's Retry-After header.
    client = BrregClient(max_retries=3)  # up to 4 attempts in total
    
    try:
        entity = await client.get_enhet("999999999")  # Will raise exception
    except BrregResourceNotFoundError:
        print("No such organization")
    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 concurrently (at most 10 requests in flight)
    org_numbers = ["923609016", "998463718", "913492978"]
    results = await client.get_multiple_enheter(org_numbers, max_concurrency=10)
    
    for org_nr, entity in results.items():
        if isinstance(entity, BrregAPIError):
            print(f"Error fetching {org_nr}: {entity}")
        else:
            print(f"{org_nr}: {entity.navn}")

📂 Project Structure

  • src/brreg_wrapper: Main package source code
    • client.py: The API client implementation
    • exceptions.py: Custom exception classes
    • models/: Pydantic models for API responses
  • examples/: Example scripts showing how to use the package
    • sample.py: Comprehensive example demonstrating key features
  • scripts/: Development utility scripts
    • test_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 UV (recommended)
uv run --extra dev pytest

# Using pip
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.

Metadata

Release files for brreg-wrapper 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brreg-wrapper 0.3.0
File Size Uploaded Provenance Actions
brreg_wrapper-0.3.0.tar.gz 51.2 kB With provenance Details for brreg_wrapper-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brreg-wrapper 0.3.0
File Interpreter ABI Platform Actions
brreg_wrapper-0.3.0-py3-none-any.whl Python 3 none any Details for brreg_wrapper-0.3.0-py3-none-any.whl

Total release size: 75.9 kB

Release files / brreg_wrapper-0.3.0.tar.gz

Download URL brreg_wrapper-0.3.0.tar.gz
Size 51.2 kB
Tags Source
SHA-256 checksum
How to use checksums
0c3caaa0440d72607cd6e512fb44a86fa9e66906922543f94b4dc5207b5fa0dd
BLAKE2b-256 checksum
How to use checksums
2509a1b32b762ca808bf5a4d9bcaf777e763ecab82985138d41e309de838d637
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 29, 2026.

Transparency log

Release files / brreg_wrapper-0.3.0-py3-none-any.whl

Download URL brreg_wrapper-0.3.0-py3-none-any.whl
Size 24.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f2b62a090fa548368d8bc5a11bbe64850c62115d529bb5b90cfdb5a0bcd3935f
BLAKE2b-256 checksum
How to use checksums
5155bec94ba4096fbdd1441cc3e9d3c2852d5306d3148e443fd1de7b95901dad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 29, 2026.

Transparency log

Security for brreg-wrapper 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for brreg_wrapper-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page