hfortix_fortios.FortiOS

class hfortix_fortios.FortiOS(host=None, token=None, *, username=None, password=None, client=None, mode='sync', verify=True, vdom=None, port=None, debug=None, debug_options=None, max_retries=3, connect_timeout=10.0, read_timeout=300.0, user_agent=None, circuit_breaker_threshold=10, circuit_breaker_timeout=30.0, circuit_breaker_auto_retry=False, circuit_breaker_max_retries=3, circuit_breaker_retry_delay=5.0, max_connections=10, max_keepalive_connections=5, session_idle_timeout=300, read_only=False, track_operations=False, adaptive_retry=False, retry_strategy='exponential', retry_jitter=False, error_mode='raise', error_format='detailed', audit_handler=None, audit_callback=None, user_context=None, trace_id=None)[source]

FortiOS REST API Client

Python client for interacting with Fortinet FortiGate firewalls via REST API. Supports configuration management (CMDB), monitoring, logging, and services.

This client uses token-based authentication and provides a stateless interface to FortiOS devices. No login/logout required - just initialize with your token and start making API calls.

Main API categories:
  • api.cmdb: Configuration Management Database (firewall policies, objects, etc.)

  • api.monitor: Real-time monitoring and status

  • api.log: Log queries and analysis

  • api.service: System services (sniffer, security rating, etc.)

Parameters:
  • host (Optional[str])

  • token (Optional[str])

  • username (Optional[str])

  • password (Optional[str])

  • client (Optional[IHTTPClient])

  • mode (Literal['sync', 'async'])

  • verify (bool)

  • vdom (Optional[str])

  • port (Union[int, str, None])

  • debug (Union[str, bool, None])

  • debug_options (Optional[dict[str, Any]])

  • max_retries (int)

  • connect_timeout (float)

  • read_timeout (float)

  • user_agent (Optional[str])

  • circuit_breaker_threshold (int)

  • circuit_breaker_timeout (float)

  • circuit_breaker_auto_retry (bool)

  • circuit_breaker_max_retries (int)

  • circuit_breaker_retry_delay (float)

  • max_connections (int)

  • max_keepalive_connections (int)

  • session_idle_timeout (Union[int, float, None])

  • read_only (bool)

  • track_operations (bool)

  • adaptive_retry (bool)

  • retry_strategy (Literal['exponential', 'linear'])

  • retry_jitter (bool)

  • error_mode (Literal['raise', 'return', 'print'])

  • error_format (Literal['detailed', 'simple', 'code_only'])

  • audit_handler (Optional[AuditHandler])

  • audit_callback (Optional[Any])

  • user_context (Optional[dict[str, Any]])

  • trace_id (Optional[str])

api

API namespace containing cmdb, monitor, log, service

Type:

API

Example:

>>> from hfortix import FortiOS
>>> fgt = FortiOS("fortigate.example.com", token="your_token_here")
>>>
>>> # List firewall addresses
>>> addresses = fgt.api.cmdb.firewall.address.get()
>>>
>>> # Create a firewall address
>>> fgt.api.cmdb.firewall.address.create(
...     name='test-host',
...     subnet='192.0.2.100/32',
...     comment='Example host'
... )
>>>
>>> # Get system status
>>> status = fgt.api.monitor.system.status.get()

Note

  • Requires FortiOS 6.0+ with REST API enabled

  • API token must be created in FortiOS: System > Admin > API Users

  • Use verify=False only in development with self-signed certificates

See also

__init__(host=None, token=None, *, username=None, password=None, client=None, mode='sync', verify=True, vdom=None, port=None, debug=None, debug_options=None, max_retries=3, connect_timeout=10.0, read_timeout=300.0, user_agent=None, circuit_breaker_threshold=10, circuit_breaker_timeout=30.0, circuit_breaker_auto_retry=False, circuit_breaker_max_retries=3, circuit_breaker_retry_delay=5.0, max_connections=10, max_keepalive_connections=5, session_idle_timeout=300, read_only=False, track_operations=False, adaptive_retry=False, retry_strategy='exponential', retry_jitter=False, error_mode='raise', error_format='detailed', audit_handler=None, audit_callback=None, user_context=None, trace_id=None)[source]

Initialize FortiOS API client (sync or async mode)

Supports two authentication methods: 1. API Token authentication (stateless, recommended for production) 2. Username/Password authentication (session-based, requires login/logout)

Parameters:
  • host (Optional[str]) – FortiGate IP/hostname (e.g., “192.0.2.10” or

  • "fortigate.example.com") – Not required if providing a custom client

  • token (Optional[str]) – API token for authentication (mutually exclusive with

  • username/password) – Not required if providing a custom client or using username/password

  • username (Optional[str]) – Username for password authentication (must be used with password) Mutually exclusive with token

  • password (Optional[str]) – Password for username authentication (must be used with username) Mutually exclusive with token

  • client (Optional[IHTTPClient]) – Optional custom HTTP client implementing IHTTPClient protocol If provided, host/token/verify/etc. are ignored and the custom client is used Allows for custom authentication, proxying, caching, etc.

  • mode (Literal['sync', 'async']) –

    Client mode - ‘sync’ (default) or ‘async’

    • ’sync’: Traditional synchronous API calls

    • ’async’: Asynchronous API calls with async/await

    Ignored if custom client is provided

  • verify (bool) – Verify SSL certificates (default: True, recommended for production)

  • vdom (Optional[str]) – Virtual domain (default: None = FortiGate’s default VDOM)

  • port (Union[int, str, None]) – HTTPS port (default: None = use 443, or specify custom port

  • 8443) (like) – Accepts both int and str types - string values are automatically converted to int. This allows passing environment variable values directly: port=os.getenv(“FORTIOS_PORT”, “443”)

  • debug (Union[str, bool, None]) – Logging level for this instance (‘debug’, ‘info’, ‘warning’,

  • 'error' – Can be a string level or boolean True for ‘debug’ level If not specified, uses the global log level set via hfortix.set_log_level()

  • 'off') – Can be a string level or boolean True for ‘debug’ level If not specified, uses the global log level set via hfortix.set_log_level()

  • debug_options (Optional[dict[str, Any]]) – Optional dict with debugging configuration options

  • max_retries (int) – Maximum number of retry attempts on transient failures

  • (default (attempts when auto-retry enabled) –

  • connect_timeout (float) – Timeout for establishing connection in seconds

  • (default – 10.0)

  • read_timeout (float) – Timeout for reading response in seconds (default:

  • 300.0)

  • user_agent (Optional[str]) – Custom User-Agent header (default: ‘hfortix/{version}’) Useful for identifying different applications/teams in FortiGate logs

  • circuit_breaker_threshold (int) – Number of consecutive failures before

  • (default

  • circuit_breaker_timeout (float) – Seconds to wait before transitioning to

  • (default – 30.0)

  • circuit_breaker_auto_retry (bool) – When True, automatically wait and retry

  • breaker (when circuit) – opens instead of raising error immediately (default: False). WARNING: Not recommended for test environments - may cause long delays.

  • circuit_breaker_max_retries (int) – Maximum number of auto-retry attempts

  • breaker – opens (default: 3). Only used when circuit_breaker_auto_retry=True.

  • circuit_breaker_retry_delay (float) – Delay in seconds between retry

  • (default – 5.0). This is separate from circuit_breaker_timeout, which controls when the circuit transitions from open to half-open.

  • max_connections (int) – Maximum number of connections in the pool

  • (default – 10) Conservative default (50% below lowest-performing device tested). Should work for most FortiGate models and network conditions. Most devices serialize API requests internally, so high concurrency doesn’t improve throughput. Increase based on performance testing: 20 for remote-wan, 30 for fast-lan, 60+ for high-performance local deployments.

  • max_keepalive_connections (int) – Maximum number of keepalive connections

  • (default – 5) Conservative default for connection reuse. If max_keepalive_connections exceeds max_connections, it will be automatically adjusted with a warning. Increase proportionally with max_connections based on your device profile.

  • session_idle_timeout (Union[int, float, None]) – For username/password auth only. Idle timeout

  • before (in seconds) – proactively re-authenticating (default: 300 = 5 minutes). This should match your FortiGate’s ‘config system global’ -> ‘remoteauthtimeout’ setting. Set to None or False to disable proactive re-authentication. Note: The idle timer resets on each API request. Proactive re-auth triggers when time since last request exceeds threshold (not time since login). API token authentication is stateless and doesn’t use sessions. Important: Proactive re-auth only works when using context manager (with statement).

  • read_only (bool) – Enable read-only mode - simulate all write operations

  • them (without executing) – (default: False). When enabled, POST/PUT/DELETE requests are logged but not sent to FortiGate. Useful for testing, dry-run, CI/CD pipelines, and training. GET requests are executed normally.

  • track_operations (bool) – Enable operation tracking - maintain audit log of

  • calls (all API) – (default: False). When enabled, all requests (GET/POST/PUT/DELETE) are recorded with timestamp, method, URL, and data. Access via get_operations() or get_write_operations(). Useful for debugging, auditing, and documentation.

  • adaptive_retry (bool) – Enable adaptive retry with backpressure detection

  • (default – False). When enabled, monitors response times and adjusts retry delays based on FortiGate health signals (slow responses, 503 errors). Increases retry delays when FortiGate is overloaded to prevent cascading failures. Access health metrics via get_health_metrics().

  • retry_strategy (Literal['exponential', 'linear']) – Retry backoff strategy (default: “exponential”). - “exponential”: 1s, 2s, 4s, 8s, 16s, 30s (recommended for transient failures) - “linear”: 1s, 2s, 3s, 4s, 5s (better for rate limiting scenarios)

  • retry_jitter (bool) – Add random jitter to retry delays (default: False). Adds 0-25% random variation to prevent thundering herd when multiple clients retry simultaneously. Recommended for production deployments.

  • error_mode (Literal['raise', 'return', 'print']) – How convenience wrappers handle errors (default:

  • "raise").

    • “raise”: Raise exceptions (stops program unless caught with try/except)

    • ”return”: Return error dict instead of raising (program always continues)

    • ”log”: Log error and return None (program always continues)

    Can be overridden per method call.

  • error_format (Literal['detailed', 'simple', 'code_only']) –

    Error message detail level (default: “detailed”).

    • ”detailed”: Full context with endpoint, parameters, and helpful hints

    • ”simple”: Just error message and code

    • ”code_only”: Just the error code number

    Can be overridden per method call. Affects both raised exceptions and returned error dicts depending on error_mode.

  • audit_handler (Optional[AuditHandler]) – Handler for enterprise audit logging (default: None). Automatically logs all API operations for compliance (SOC 2, HIPAA, PCI-DSS). Use built-in handlers: SyslogHandler (SIEM), FileHandler (local logs), StreamHandler (container logs), CompositeHandler (multiple destinations). Example: SyslogHandler(“siem.company.com:514”)

  • audit_callback (Optional[Any]) – Custom callback function for audit logging

  • (default – None). Alternative to audit_handler. Called with operation dict for each API call. Use for custom logging destinations (Kafka, database, cloud services). Example: lambda op: send_to_kafka(op)

  • user_context (Optional[dict[str, Any]]) – Optional user/application context for audit logs

  • (default – None). Dict with metadata to include in every audit entry. Useful for tracking which user/script/ticket caused each change. Example: {“username”: “admin”, “app”: “backup_script”, “ticket”: “CHG-12345”}

  • trace_id (Optional[str]) – Optional distributed tracing ID for request correlation

  • (default – None). String identifier to track requests across multiple systems. Automatically included in user_context and all audit logs. Useful for debugging and distributed tracing systems (Jaeger, Zipkin, etc.). Example: “request-12345” or UUID

Return type:

None

Important

Username/password authentication still works in FortiOS 7.4.x but is removed in FortiOS 7.6.x and later. Use API token authentication for production deployments.

Performance Note:

Most FortiGate devices serialize API requests internally, meaning concurrent requests don’t improve throughput and actually increase response times (10-15x slower). Sequential requests are recommended for most deployments. Use async mode only when integrating with async frameworks or managing multiple devices in parallel. Performance testing shows ~5 req/s for most devices, ~30 req/s for high-performance local deployments. See COMPARATIVE_ANALYSIS.md for detailed performance profiles.

Examples:

# Token authentication (recommended)
fgt = FortiOS("fortigate.example.com", token="your_token_here",
verify=True)
addresses = fgt.api.cmdb.firewall.address.get("test-host")

# Enterprise audit logging to SIEM (compliance)
from hfortix_core.audit import SyslogHandler
fgt = FortiOS("192.0.2.10", token="token",
             audit_handler=SyslogHandler("siem.company.com:514"))
# All API operations now logged to SIEM automatically

# Multi-destination audit logging
from hfortix_core.audit import CompositeHandler, FileHandler,
StreamHandler
handler = CompositeHandler([
    SyslogHandler("siem.company.com:514"),  # Compliance
    FileHandler("/var/log/fortinet-audit.jsonl"),  # Backup
])
fgt = FortiOS("192.0.2.10", token="token", audit_handler=handler)

# Custom audit callback
def my_audit(op):
    send_to_kafka(op)
    update_cmdb(op)
fgt = FortiOS("192.0.2.10", token="token",
audit_callback=my_audit)

# Audit logging with user context
fgt = FortiOS("192.0.2.10", token="token",
             audit_handler=SyslogHandler("siem.company.com:514"),
             user_context={"username": "admin", "ticket":
             "CHG-12345"})

# Distributed tracing with trace_id
fgt = FortiOS("192.0.2.10", token="token",
             trace_id="request-abc123",
             audit_handler=SyslogHandler("siem.company.com:514"))
# trace_id automatically added to all audit logs and user_context

# Username/Password authentication with context manager (sync)
with FortiOS("192.0.2.10", username="admin", password="password",
verify=False) as fgt:
    addresses = fgt.api.cmdb.firewall.address.get("test-host")
    # Auto-logout on exit

# Username/Password authentication with context manager (async)
async with FortiOS("192.0.2.10", username="admin",
password="password",
                  mode="async", verify=False) as fgt:
    status = await fgt.api.monitor.system.status.get()
    # Auto-logout on exit

# Asynchronous mode with token
fgt = FortiOS("fortigate.example.com", token="your_token_here",
mode="async")
addresses = await fgt.api.cmdb.firewall.address.get("test-host")

# Custom HTTP client
class MyHTTPClient:
    def get(self, api_type, path, **kwargs):
        # Custom implementation with company auth, logging, etc.
        ...
    def post(self, api_type, path, data, **kwargs):
        ...
    # ... put, delete

fgt = FortiOS(client=MyHTTPClient())
addresses = fgt.api.cmdb.firewall.address.get("test-host")

# Production - with valid SSL certificate
fgt = FortiOS("fortigate.example.com", token="your_token_here",
verify=True)

# Development/Testing - with self-signed certificate (example IP from RFC 5737)  # noqa: E501
fgt = FortiOS("192.0.2.10", token="your_token_here", verify=False)

# Environment variables (credentials from environment)
# Set: export FORTIOS_HOST="192.0.2.10"
#      export FORTIOS_TOKEN="your_token_here"
fgt = FortiOS()  # Reads from FORTIOS_HOST, FORTIOS_TOKEN

# Environment variables with username/password
# Set: export FORTIOS_HOST="192.0.2.10"
#      export FORTIOS_USERNAME="admin"
#      export FORTIOS_PASSWORD="your_password"
fgt = FortiOS()  # Reads from FORTIOS_HOST, FORTIOS_USERNAME,
FORTIOS_PASSWORD

# Environment variables with custom port
# Set: export FORTIOS_HOST="192.0.2.10"
#      export FORTIOS_TOKEN="your_token_here"
#      export FORTIOS_PORT="8443"
fgt = FortiOS()  # Reads from FORTIOS_HOST, FORTIOS_TOKEN, FORTIOS_PORT

# Custom port
fgt = FortiOS("192.0.2.10", token="your_token_here", verify=False,
port=8443)

# Port in hostname (alternative)
fgt = FortiOS("192.0.2.10:8443", token="your_token_here",
verify=False)

# Enable debug logging for this instance only
fgt = FortiOS("192.0.2.10", token="your_token_here", verify=False,
debug='info')

# Custom timeouts (e.g., slower network)
fgt = FortiOS("192.0.2.10", token="your_token_here",
connect_timeout=30.0, read_timeout=600.0)

# Custom User-Agent for multi-team environments
fgt = FortiOS("192.0.2.10", token="your_token_here",
user_agent="BackupScript/2.1.0")

# Read-only mode for testing (simulates writes without executing)
fgt = FortiOS("192.0.2.10", token="your_token_here",
read_only=True)
fgt.api.cmdb.firewall.address.create(name="test")  # Logged but not
executed

# Operation tracking for debugging/auditing
fgt = FortiOS("192.0.2.10", token="your_token_here",
track_operations=True)
fgt.api.cmdb.firewall.address.create(name="test",
subnet="10.0.0.1/32")
operations = fgt.get_operations()  # Get all operations
write_ops = fgt.get_write_operations()  # Only POST/PUT/DELETE

Methods

__init__([host, token, username, password, ...])

Initialize FortiOS API client (sync or async mode)

aclose()

Close the async HTTP session and release resources (async mode only)

close()

Close the HTTP session and release resources

export_audit_logs([filepath, format, ...])

Export audit logs to file or return as string

get_circuit_breaker_state()

Get current circuit breaker state

get_connection_stats()

Get HTTP connection pool statistics and metrics

get_health_metrics()

Get comprehensive health metrics for HTTP client

get_operations()

Get audit log of all API operations (requires track_operations=True)

get_retry_stats()

Get retry statistics from HTTP client

get_write_operations()

Get audit log of write operations only (requires track_operations=True)

list_transactions()

List all active transactions on the FortiGate

request(config)

Execute a generic API request from FortiGate GUI API preview JSON

transaction([timeout, vdom, auto_commit, ...])

Create a FortiOS batch transaction context manager

transactional([timeout, vdom])

Decorator to run a function within a FortiOS transaction

Attributes

api

Primary entry point to FortiOS endpoints (cmdb/monitor/log/service).

connection_stats

Get connection pool and health statistics

error_format

Default error message format for convenience wrappers

error_mode

Default error handling mode for convenience wrappers

host

FortiGate hostname or IP address

last_request

Get details of last API request (for debugging)

port

HTTPS port number

vdom

Active virtual domain