api config library
Project description
apiconfig
Flexible, extensible configuration and authentication for Python API clients.
Table of Contents
- Project Overview
- Quickstart
- Installation
- Key Features
- Usage
- Practical Example: Real API Client Setup
- Logging
- Error Handling
- Testing and Coverage
- CI/CD
- Further Documentation
- License
Project Overview
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.
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.
Usage
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:
APIConfigErrorConfigurationErrorAuthenticationErrorInvalidConfigErrorMissingConfigErrorAuthStrategyError
Testing and Coverage
apiconfig is fully tested with pytest and coverage.py. To run tests and check coverage:
pytest --cov=apiconfig --cov-report=html
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.
Further Documentation
- Documentation (latest)
- CONTRIBUTING.md — Contribution guidelines
- Bug Tracker
- PyPI Project Page
License
LGPL-3.0-or-later. See LICENSE for details.
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 apiconfig-0.3.2.dev289.tar.gz.
File metadata
- Download URL: apiconfig-0.3.2.dev289.tar.gz
- Upload date:
- Size: 86.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1679bfc0b8cca417774c7832f5da8fb1c6d4aede30f4444ededd7400c9017190
|
|
| MD5 |
834b76bf2db9aaeecf39a3a3d44e4705
|
|
| BLAKE2b-256 |
1366d69f3325f7c86d35bb59e5eb04f80c0be76ae6eeb1ffbc3301c2415be7a1
|
Provenance
The following attestation bundles were made for apiconfig-0.3.2.dev289.tar.gz:
Publisher:
publish.yaml on Leikaab/apiconfig
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
apiconfig-0.3.2.dev289.tar.gz -
Subject digest:
1679bfc0b8cca417774c7832f5da8fb1c6d4aede30f4444ededd7400c9017190 - Sigstore transparency entry: 234887998
- Sigstore integration time:
-
Permalink:
Leikaab/apiconfig@2e63115e87200752d78cbe1fbb939eea07147ef8 -
Branch / Tag:
refs/heads/develop - Owner: https://github.com/Leikaab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yaml@2e63115e87200752d78cbe1fbb939eea07147ef8 -
Trigger Event:
push
-
Statement type:
File details
Details for the file apiconfig-0.3.2.dev289-py3-none-any.whl.
File metadata
- Download URL: apiconfig-0.3.2.dev289-py3-none-any.whl
- Upload date:
- Size: 117.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dfb75cee4256be64632a789662b075df972d104d1baafdaf3a2eb8db6f985ee6
|
|
| MD5 |
1db3be9a50544f1b605684e87e3a73b9
|
|
| BLAKE2b-256 |
2787a56167957d5ce91ed1855dfcf0e39af24cc55fff5b9a9dc889520e95e08c
|
Provenance
The following attestation bundles were made for apiconfig-0.3.2.dev289-py3-none-any.whl:
Publisher:
publish.yaml on Leikaab/apiconfig
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
apiconfig-0.3.2.dev289-py3-none-any.whl -
Subject digest:
dfb75cee4256be64632a789662b075df972d104d1baafdaf3a2eb8db6f985ee6 - Sigstore transparency entry: 234888020
- Sigstore integration time:
-
Permalink:
Leikaab/apiconfig@2e63115e87200752d78cbe1fbb939eea07147ef8 -
Branch / Tag:
refs/heads/develop - Owner: https://github.com/Leikaab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yaml@2e63115e87200752d78cbe1fbb939eea07147ef8 -
Trigger Event:
push
-
Statement type: