Skip to main content

apiconfig

Flexible, extensible configuration and authentication for Python API clients.

PyPI - Python Version PyPI - Version Test Status Publish to PyPI


Table of Contents

Documentation

Module Description

apiconfig is a standalone Python library for managing API client configuration and authentication. It provides a robust, extensible foundation for building API clients, handling configuration (base URLs, timeouts, retries, headers) and supporting multiple authentication strategies (API key, Basic, Bearer, custom).

apiconfig is designed for:

  • Developers building reusable, testable API clients.
  • Projects needing flexible configuration sources (env, file, memory).
  • Secure, pluggable authentication for HTTP APIs.

Navigation


Contents

apiconfig/
├── auth/          # Authentication strategies (basic, bearer, API key, custom)
├── config/        # API client configuration and providers
├── exceptions/    # Structured exception hierarchy
├── testing/       # Test utilities and helpers
├── utils/         # Logging, redaction, and utilities
└── types.py       # Shared type definitions

Usage Examples

Quickstart

pip install apiconfig
from apiconfig import ClientConfig, ApiKeyAuth

auth = ApiKeyAuth(api_key="my-secret-key", header_name="X-API-Key")
config = ClientConfig(
    hostname="api.example.com",
    version="v1",
    auth_strategy=auth,
    timeout=10.0,
    retries=3,
)
print(config.base_url)  # https://api.example.com/v1

Installation

Install from PyPI:

pip install apiconfig

Or with Poetry:

poetry add apiconfig

Key Features

  • Unified API Client Configuration: Manage base URLs, versions, headers, timeouts, retries, and more with a single, validated config object.
  • Authentication Strategies: Built-in support for API Key, Basic, Bearer, and custom authentication via the Strategy Pattern.
  • Config Providers: Load configuration from environment variables, files, or in-memory sources.
  • Extensible: Easily add new authentication methods or config providers.
  • Robust Error Handling: Clear, structured exception hierarchy for all config and auth errors.
  • Type Safety: Strong type hints and type-checked public API.
  • Logging Integration: Standard logging hooks for debugging and auditability.
  • High Test Coverage: Around 94% coverage with unit and integration tests.

Basic Configuration

from apiconfig import ClientConfig

config = ClientConfig(
    hostname="api.example.com",
    version="v1",
    headers={"X-My-Header": "value"},
    timeout=10.0,
    retries=3,
)
print(config.base_url)  # https://api.example.com/v1

Authentication Strategies

API Key in Header

from apiconfig import ClientConfig, ApiKeyAuth

auth = ApiKeyAuth(api_key="my-secret-key", header_name="X-API-Key")
config = ClientConfig(
    hostname="api.example.com",
    version="v1",
    auth_strategy=auth,
)

API Key in Query Parameter

from apiconfig import ApiKeyAuth

auth = ApiKeyAuth(api_key="my-secret-key", param_name="api_key")

Basic and Bearer Auth

from apiconfig import BasicAuth, BearerAuth

basic = BasicAuth(username="user", password="pass")
bearer = BearerAuth(access_token="my-jwt-token")

Custom Authentication

from apiconfig import CustomAuth

custom = CustomAuth(auth_callable=lambda: {"Authorization": "Custom xyz"})

Using Configuration Providers

Environment Variables

from apiconfig import EnvProvider

env = EnvProvider(prefix="MYAPI_")
config_dict = env.load()
# Example: MYAPI_HOSTNAME=api.example.com, MYAPI_TIMEOUT=5

File and Memory Providers

from apiconfig import FileProvider, MemoryProvider

file_provider = FileProvider(file_path="config.json")
file_config = file_provider.load()

# MemoryProvider accepts configuration via the ``config_data`` parameter and
# exposes ``get_config`` instead of ``load``
memory_provider = MemoryProvider(config_data={"hostname": "api.example.com"})
memory_config = memory_provider.get_config()

Merging Configurations

from apiconfig import ClientConfig

base = ClientConfig(hostname="api.example.com", timeout=10)
override = ClientConfig(timeout=5, retries=2)
merged = base.merge(override)

Practical Example: Real API Client Setup

Below is a real-world example based on the integration tests. This pattern demonstrates how to use apiconfig to load configuration and secrets from environment variables, set up authentication, and make a request with an HTTP client (e.g., httpx):

import os
import httpx
from apiconfig import EnvProvider, ClientConfig, BearerAuth

# Load config and secrets from environment variables
env = EnvProvider()
config_dict = env.load()

# Get token and base URL from environment or use defaults
access_token = config_dict.get("FIKEN_ACCESS_TOKEN") or os.environ.get("FIKEN_ACCESS_TOKEN")
base_url = config_dict.get("FIKEN_BASE_URL") or os.environ.get("FIKEN_BASE_URL") or "https://api.fiken.no/api/v2"

# Set up authentication strategy if token is available
auth_strategy = BearerAuth(access_token) if access_token else None

# Create the API client configuration
client_config = ClientConfig(
    hostname=base_url,
    auth_strategy=auth_strategy,
)

# Prepare request headers using the auth strategy
headers = {}
if client_config.auth_strategy is not None:
    headers.update(client_config.auth_strategy.prepare_request_headers())

# Make a real HTTP request using httpx
with httpx.Client(timeout=10.0) as client:
    response = client.get(f"{client_config.base_url}/companies", headers=headers)
    print(response.status_code, response.json())

This approach can be adapted for any API and authentication method supported by apiconfig. See the integration tests for more real-world examples.


Logging

apiconfig uses standard Python logging. To enable debug output:

import logging

logging.basicConfig(level=logging.DEBUG)
logging.getLogger("apiconfig").setLevel(logging.INFO)

Error Handling

All errors are structured and documented. Common exceptions include:

  • APIConfigError
  • ConfigurationError
  • AuthenticationError
  • InvalidConfigError
  • MissingConfigError
  • AuthStrategyError

Key Components

Alias Description
JsonObject Dictionary representing a JSON object
HeadersType Mapping of HTTP header names to values
QueryParamType Mapping for URL query parameters
DataType HTTP request body data
ResponseBodyType API response body

Architecture

Class Hierarchy

classDiagram
    ClientConfig --> AuthStrategy : uses
    ConfigManager --> ClientConfig : manages
    AuthStrategy <|-- ApiKeyAuth
    AuthStrategy <|-- BasicAuth
    AuthStrategy <|-- BearerAuth

Authentication Flow

sequenceDiagram
    participant Client
    participant AuthStrategy
    participant HTTPClient

    Client->>AuthStrategy: prepare_request_headers()
    AuthStrategy-->>Client: headers
    Client->>HTTPClient: request with headers

    alt token expired
        HTTPClient-->>Client: 401
        Client->>AuthStrategy: refresh()
        AuthStrategy-->>Client: new token
        Client->>HTTPClient: retry request
    end

Testing

Testing and Coverage

apiconfig is fully tested with pytest and coverage.py. To run tests and check coverage:

pytest --cov=apiconfig --cov-report=html

Static Type Checking

apiconfig uses Pyright for optional static type checking. Before running Pyright, ensure development dependencies are installed and the virtual environment is active:

poetry install --with dev
poetry shell
pyright

This guarantees libraries like httpx, pytest, and their stubs are available.

Test Structure

Unit tests are organized by feature under tests/unit. The exception hierarchy is covered in tests/unit/exceptions.

Test Dependencies

Tests rely only on pytest and the apiconfig package; no external services are required.


Running tests

Use pytest to execute the full test suite:

poetry run pytest

Test Structure

  • tests/unit – unit tests
  • tests/integration – integration tests against real APIs

Test Dependencies

  • Install dev dependencies with poetry install --with dev
  • Environment variables for integration tests are loaded automatically

CI/CD

Continuous integration and deployment are managed with GitHub Actions. All pushes and pull requests are tested, and releases are published to PyPI after passing tests.


Dependencies

External

Internal

  • Modules like apiconfig.config, apiconfig.auth, and apiconfig.utils

Optional

Optional Dependencies

None

Install development dependencies with:

poetry install --with dev

Status

Stability: Stable - the project is actively used in production environments. API Version: Follows Semantic Versioning starting at version 0.x. Deprecations: None

Maintenance Notes

The library is currently stable and actively maintained. Issues and pull requests are triaged on a best-effort basis. Minor feature requests and fixes are welcome.

Changelog

See CHANGELOG.md for a complete history of changes.

Future Considerations

Planned improvements include enhanced documentation, additional auth strategies, expanded test coverage, and formatter enhancements for more consistent styling.

Further Documentation


See Also


License

LGPL-3.0-or-later. See LICENSE for details.

Metadata

Release files for apiconfig 0.3.4

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

Source distribution (sdist)

Source distribution for apiconfig 0.3.4
File Size Uploaded Provenance
apiconfig-0.3.4.tar.gz 104.9 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for apiconfig 0.3.4
File Interpreter ABI Platform
apiconfig-0.3.4-py3-none-any.whl Python 3 none any Details

Total release size: 249.1 kB

Release files / apiconfig-0.3.4.tar.gz

Download URL apiconfig-0.3.4.tar.gz
Size 104.9 kB
Tags Source
SHA-256 checksum
How to use checksums
9e8621ec96b2b0b9e1f4a43e9589ba99ff36b855b5beb91115057044585f772d
BLAKE2b-256 checksum
How to use checksums
ddb8dff9e411109f1ac7d52e8980ce169f36272ae15d2ab6ede090192651f583
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 Oct 9, 2026.

Transparency log

Release files / apiconfig-0.3.4-py3-none-any.whl

Download URL apiconfig-0.3.4-py3-none-any.whl
Size 144.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cb2febac2859c7af10567a7a515d7159cd487e14fdccd2b7d155ca9013cbf190
BLAKE2b-256 checksum
How to use checksums
392272027791d100354463e014c6386466605f90ed7b0f3866aa409bb51aa757
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 Oct 9, 2026.

Transparency log

Security for apiconfig 0.3.4

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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for apiconfig-0.3.4.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 Oct 9, 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.

Release history Release notifications | RSS feed

This release

0.3.4 This release

2 release files Full provenance

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