Skip to content

init

FMG API library

AnyFMG module-attribute #

AnyFMG = Union[FMG, AsyncFMG]

AnyFMGObject module-attribute #

AnyFMGObject = TypeVar('AnyFMGObject', FMGObject, FMGExecObject)

GetOption module-attribute #

GetOption = Literal[
    "extra info",
    "assignment info",
    "loadsub",
    "no loadsub",
    "count",
    "syntax",
    "devinfo",
    "obj flags",
    "datasrc",
    "chksum",
]

FMGBaseObject #

FMGBaseObject(*args, **kwargs)

Bases: BaseModel, ABC

Abstract base object for all high-level objects

Scope must be set before referencing the url! It's done by FMGBase requests as it defaults all objects to its selected ADOM.

In case of AsyncFMG, caller must ensure await-ing the request.

Attributes:

Name Type Description
fmg_scope str

FMG selected scope (adom or global)

_version str

Supported API version

_url str

template for API URL

_fmg FMG

FMG instance

Other Parameters:

Name Type Description
scope str

FMG selected scope (adom or global)

fmg AnyFMG

FMG instance

Source code in pyfortinet/fmg_api/__init__.py
def __init__(self, *args, **kwargs) -> None:
    """Initialize FMGObject

    Keyword Args:
        scope (str): FMG selected scope (adom or global)
        fmg (AnyFMG): FMG instance
    """
    super().__init__(*args, **kwargs)
    self.fmg_scope = kwargs.get("fmg_scope")
    self._fmg: "AnyFMG" = kwargs.get("fmg")

fmg_scope property writable #

fmg_scope: str

Object scope (adom)

get_url #

get_url(method: Literal['get', 'add', 'set', 'update', 'delete', 'clone', 'exec'] = 'exec') -> str

General API URL assembly

To be overridden by more complex API URLs in different classes

Source code in pyfortinet/fmg_api/__init__.py
def get_url(self, method: Literal["get", "add", "set", "update", "delete", "clone", "exec"] = "exec") -> str:
    """General API URL assembly

    To be overridden by more complex API URLs in different classes
    """
    if not self.fmg_scope:
        if "{scope}" in self._url:
            raise FMGMissingScopeException(f"Missing scope for {self}")
        return self._url
    url = self._url.replace("{scope}", self.fmg_scope)
    return url

FMGExecObject #

FMGExecObject(*args, **kwargs)

Bases: FMGBaseObject, ABC

FMG execute job type

Attributes:

Name Type Description
fmg_scope str

FMG selected scope (adom or global)

_version str

Supported API version

_url str

template for API URL

_fmg FMG

FMG instance

Source code in pyfortinet/fmg_api/__init__.py
def __init__(self, *args, **kwargs) -> None:
    """Initialize FMGObject

    Keyword Args:
        scope (str): FMG selected scope (adom or global)
        fmg (AnyFMG): FMG instance
    """
    super().__init__(*args, **kwargs)
    self.fmg_scope = kwargs.get("fmg_scope")
    self._fmg: "AnyFMG" = kwargs.get("fmg")

exec #

exec()

Exec FMG operation on this object

Source code in pyfortinet/fmg_api/__init__.py
def exec(self):
    """Exec FMG operation on this object"""
    if self._fmg:
        return self._fmg.exec(self)
    raise FMGNotAssignedException

FMGObject #

FMGObject(*args, **kwargs)

Bases: FMGBaseObject, ABC

Abstract base object for all high-level objects

Scope must be set before referencing the url! It's done by FMGBase requests as it defaults all objects to its selected ADOM.

In case of AsyncFMG, caller must ensure await-ing the request.

Attributes:

Name Type Description
fmg_scope str

FMG selected scope (adom or global)

_version str

Supported API version

_url str

template for API URL

_fmg FMG

FMG instance

_master_keys str

attributes which represents unique key in FMG DB for this API class

Source code in pyfortinet/fmg_api/__init__.py
def __init__(self, *args, **kwargs) -> None:
    """Initialize FMGObject

    Keyword Args:
        scope (str): FMG selected scope (adom or global)
        fmg (AnyFMG): FMG instance
    """
    super().__init__(*args, **kwargs)
    self.fmg_scope = kwargs.get("fmg_scope")
    self._fmg: "AnyFMG" = kwargs.get("fmg")

master_keys property #

master_keys: dict[str, str]

Dict of fields where key is URL attribute and value is model field

Example of master_keys definition: URL: /pm/config/{scope}/obj/firewall/addrgrp/{addrgrp} master_keys = {"addrgrp": "name"}

Here "addrgrp" is the URL field to be replaced by the model field "name"

add #

add()

Add this object to FMG

Source code in pyfortinet/fmg_api/__init__.py
def add(self):
    """Add this object to FMG"""
    if self._fmg:
        return self._fmg.add(self)
    raise FMGNotAssignedException

clone #

clone(create_task: bool = False, **new: str)

Clone this object to a new one

Source code in pyfortinet/fmg_api/__init__.py
def clone(self, create_task: bool = False, **new: str):
    """Clone this object to a new one"""
    if self._fmg:
        return self._fmg.clone(self, create_task=create_task, **new)
    raise FMGNotAssignedException

delete #

delete()

Delete FMG operation on this object

Source code in pyfortinet/fmg_api/__init__.py
def delete(self):
    """Delete FMG operation on this object"""
    if self._fmg:
        return self._fmg.delete(self)
    raise FMGNotAssignedException

get_url #

get_url(method: Literal['get', 'add', 'set', 'update', 'delete', 'clone', 'exec'] = 'get') -> str

General API URL assembly

To be overridden by more complex API URLs in different classes

Source code in pyfortinet/fmg_api/__init__.py
def get_url(self, method: Literal["get", "add", "set", "update", "delete", "clone", "exec"] = "get") -> str:
    """General API URL assembly

    To be overridden by more complex API URLs in different classes
    """
    variables = re.findall(r"{(.*?)}", self._url)
    if not self.fmg_scope:
        if "scope" in variables:
            raise FMGMissingScopeException(f"Missing scope for {self}")
    url = self._url
    for field in variables:
        if field == "scope":
            url = url.replace(f"{{{field}}}", self.fmg_scope)
        else:
            if hasattr(self, field) and getattr(self, field) is not None:
                url = url.replace(f"{{{field}}}", str(getattr(self, field)))
            elif (
                method in ("get", "set", "update", "delete", "clone")
                and field in self.master_keys
                and getattr(self, self.master_keys[field], None) is not None
            ):  # certain methods require master key (like policyid)
                url = url.replace(f"{{{field}}}", str(getattr(self, self.master_keys[field])))
            # delete field from URL if no data found (can lead to errors)
            elif method in ("get", "add", "set", "update") and url.endswith(f"{{{field}}}"):
                url = url.replace(f"/{{{field}}}", "")
            else:
                raise FMGInvalidURL(f"Missing field '{field}' for ({self._url})")
    return url

model_dump_for_filter #

model_dump_for_filter() -> dict

Modified pydantic model dump for FMG API

This method will include otherwise excluded fields to use them in FMG.get method filtering. Special attention is made for URL fields which must not be included in the filters as they are not part of the payload.

Source code in pyfortinet/fmg_api/__init__.py
def model_dump_for_filter(self) -> dict:
    """Modified pydantic model dump for FMG API

    This method will include otherwise excluded fields to use them in FMG.get method filtering.
    Special attention is made for URL fields which must not be included in the filters as they are not part of the
    payload.
    """
    # get the normal dump first
    dump = self.model_dump(by_alias=True, exclude_none=True)
    # include excluded not-none fields
    excluded_fields = {}
    for field_name, field_model in type(self).model_fields.items():
        # check only excluded vars which are not None and are not URL attributes (cannot be used as filter)
        if field_model.exclude and getattr(self, field_name) is not None and f"{{{field_name}}}" not in self._url:
            excluded_fields[field_model.serialization_alias or field_name] = getattr(self, field_name)

    dump.update(excluded_fields)
    return dump

refresh #

refresh()

Re-load data from FMG

Source code in pyfortinet/fmg_api/__init__.py
def refresh(self):
    """Re-load data from FMG"""
    if self._fmg:
        return self._fmg.refresh(self)
    raise FMGNotAssignedException

set #

set()

Set FMG operation on this object

Source code in pyfortinet/fmg_api/__init__.py
def set(self):
    """Set FMG operation on this object"""
    if self._fmg:
        return self._fmg.set(self)
    raise FMGNotAssignedException

update #

update()

Update FMG operation on this object

Source code in pyfortinet/fmg_api/__init__.py
def update(self):
    """Update FMG operation on this object"""
    if self._fmg:
        return self._fmg.update(self)
    raise FMGNotAssignedException