Skip to main content

Core foundation for HFortix - Fully-typed Fortinet SDK with async support and type safety

Project description

HFortix-Core

PyPI version Python 3.10+ Documentation Status License Typing: Typed

HFortix-Core is the shared foundation for the HFortix ecosystem: HTTP client infrastructure (REST, JSON-RPC, and FortiCloud OAuth2), a complete exception hierarchy, retry/circuit-breaker/rate-limit resilience, audit and structured logging, caching, and formatting utilities.

🚀 Quick Start

pip install hfortix-core

Note: This is a foundational library. Most users should install hfortix-fortios (FortiGate), hfortix-fortimanager, hfortix-forticare, hfortix-fortiztp, or the hfortix meta-package instead.

Direct usage — FortiOS REST client:

from hfortix_core.http import HTTPClient
from hfortix_core import APIError, RetryableError

client = HTTPClient(
    url="https://192.168.1.99",
    token="your-api-token",
    verify=True,
    max_retries=3,
)

try:
    # The client prepends /api/v2/<api_type>/ — pass only the endpoint path
    response = client.get("cmdb", "firewall/policy")
except RetryableError as e:
    print(f"Transient failure after retries: {e.message}")
except APIError as e:
    print(f"API error: {e.message} (HTTP {e.http_status})")
finally:
    client.close()

FortiManager / FortiAnalyzer JSON-RPC client:

from hfortix_core import HTTPClientJSONRPC

fmg = HTTPClientJSONRPC(
    url="https://fmg.example.com",
    username="admin",
    password="password",
)
fmg.login()
result = fmg.execute("get", [{"url": "/dvmdb/adom/root/device"}])
fmg.logout()

FortiCloud (FortiCare / FortiZTP) OAuth2 session:

from hfortix_core.session import CloudSession

with CloudSession(api_id="your-api-id", password="your-password") as session:
    token = session.get_token("assetmanagement")  # per-service OAuth2 token

📦 What's Included

HTTP Client Framework (hfortix_core.http)

All clients subclass BaseHTTPClient and share retry logic, opt-in circuit breaker and rate limiting, connection pooling (HTTP/2 via httpx), audit/debug hooks, and request statistics:

  • HTTPClient / AsyncHTTPClient — FortiOS REST (used by hfortix-fortios)
  • HTTPClientJSONRPC — FortiManager/FortiAnalyzer JSON-RPC (HTTPClientFMG remains as a backwards-compatibility alias)
  • CloudHTTPClient — FortiCloud REST with OAuth2 bearer tokens (used by hfortix-forticare and hfortix-fortiztp)
  • FortiCloudAuth / get_oauth_token — FortiCloud OAuth2 token acquisition
  • IHTTPClient — protocol interface for injecting custom clients

Resilience (opt-in)

Both features are disabled by default and enabled via constructor keywords on any client:

client = HTTPClient(
    url="https://192.168.1.99",
    token="...",
    rate_limit=True,                 # client-side throttling
    rate_limit_max_requests=100,
    rate_limit_window_seconds=60.0,
    rate_limit_strategy="queue",     # "queue" | "drop" | "raise"
    circuit_breaker=True,            # fail fast when the device is down
    circuit_breaker_threshold=5,
    circuit_breaker_timeout=60.0,
)

RateLimitStats additionally provides enforcement-free tracking of call and error rates across 1-minute/5-minute/1-hour windows.

Exception Hierarchy (hfortix_core.exceptions)

One hierarchy for every HFortix package, rooted at FortinetError, with an explicit retry split under APIError:

  • RetryableErrorRateLimitError (429), ServerError (500), ServiceUnavailableError (503), TimeoutError, CircuitBreakerOpenError
  • NonRetryableErrorBadRequestError (400), ResourceNotFoundError (404), MethodNotAllowedError (405), DuplicateEntryError, EntryInUseError, InvalidValueError, PermissionDeniedError
  • AuthenticationError / AuthorizationError inherit directly from FortinetError (not APIError) — catch them explicitly
  • Every exception exposes .message (original message) plus rich context (http_status, error_code, endpoint, hint, ...) on APIError
  • Helpers: raise_for_status() (maps ~300 FortiOS error codes), is_retryable_error(), get_retry_delay(), get_error_description()

Session Management (hfortix_core.session)

  • CloudSession — multi-service OAuth2 token management with per-client_id token sharing, optional background refresh, pluggable token storage backends, and lifecycle hooks

Utilities

  • TTLCache — simple in-memory TTL cache for readonly reference data
  • fmt — output formatting helpers (to_table, to_json, to_yaml, to_csv, to_markdown_table, to_xml, and more)
  • Audit logging (hfortix_core.audit) — Syslog/File/Stream/Composite handlers with JSON/CEF/Syslog formatters for compliance logging
  • Structured logging (hfortix_core.logging) and debug tooling (hfortix_core.debug)
  • TypedDict definitions (hfortix_core.types) — PEP 561 typed distribution

🔗 Related Packages

📚 Documentation

🤝 Contributing

This is a proprietary library. For support or feature requests, please contact the maintainer.

📄 License

Proprietary License - See LICENSE file for details.


Part of the HFortix ecosystem - Modern Python SDKs for Fortinet automation

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

hfortix_core-0.5.165.tar.gz (132.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hfortix_core-0.5.165-py3-none-any.whl (145.7 kB view details)

Uploaded Python 3

File details

Details for the file hfortix_core-0.5.165.tar.gz.

File metadata

  • Download URL: hfortix_core-0.5.165.tar.gz
  • Upload date:
  • Size: 132.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for hfortix_core-0.5.165.tar.gz
Algorithm Hash digest
SHA256 c2dd9cd5f28807c81e2f9eebf30fec9137b0b587d0aab80bf28e211083c4643f
MD5 4e54a3e2a17a603bd840c3022ac7a468
BLAKE2b-256 a613a6af2ba03683e22d140df1958b9e5fd08b9349ddce9f3e6eb86e4f163aa1

See more details on using hashes here.

File details

Details for the file hfortix_core-0.5.165-py3-none-any.whl.

File metadata

  • Download URL: hfortix_core-0.5.165-py3-none-any.whl
  • Upload date:
  • Size: 145.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for hfortix_core-0.5.165-py3-none-any.whl
Algorithm Hash digest
SHA256 77b620d546ad72754be900f81e62d6d6b5da7b24cc1901a37953520613a6893f
MD5 c0ad9f1fd23aca44feca1982bd38fbcc
BLAKE2b-256 8574a92d40e4b952f7e8e7b8fd340ac83052b350f0711d7b78bbd08f3e9d82ab

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page