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.164.tar.gz (131.7 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.164-py3-none-any.whl (145.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: hfortix_core-0.5.164.tar.gz
  • Upload date:
  • Size: 131.7 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.164.tar.gz
Algorithm Hash digest
SHA256 73cd3be2d3ba669fedbf0082716c38f98c247718a2257e1d6e130fa532067281
MD5 50abe8997c4ebd8994424b1eea056cfc
BLAKE2b-256 153a89538532ebffe65c88534508b6f47bf36101e1ff1af124a8fa545867bbde

See more details on using hashes here.

File details

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

File metadata

  • Download URL: hfortix_core-0.5.164-py3-none-any.whl
  • Upload date:
  • Size: 145.2 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.164-py3-none-any.whl
Algorithm Hash digest
SHA256 fd0e056b141859e5e541562e997b13adc8a5f220f87ee939d77e12b91b50ff2a
MD5 f8ae1d8814d334bc8f0f9b5dad3ce4d1
BLAKE2b-256 9d702693131de341074c1e34e8fd1ee7b2564b323660d9d8573aef0c4a41c702

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