Skip to content

Client

The MregClient is the entry point to the library. It owns the HTTP session, authentication state, cache, request log, and event log, and exposes every resource type as a manager attribute (see Managers).

For a task-oriented introduction, see Client configuration and Authentication.

MregClient

Client for interacting with MREG API.

This client manages HTTP sessions, authentication, and provides methods for making API requests.

Authentication modes:

  1. Username/password: Call login() with credentials
  2. Token: Provide token directly via set_token()

Example:

>>> client = MregClient(url="https://mreg.example.com", domain="example.com")
>>> client.login("username", "password")

# Or with token:
>>> client = MregClient(url="https://mreg.example.com", domain="example.com")
>>> client.set_token("your-token-here")

atom cached property

Manage host policy atoms.

bacnetid cached property

bacnetid: BacnetIDManager

Manage BACnet IDs.

cname cached property

cname: CNAMEManager

Manage CNAME records.

community cached property

community: CommunityManager

Manager for network community resources.

delegation cached property

delegation: DelegationManager

Manage zone delegations.

dhcphostipv4 cached property

dhcphostipv4: DhcpHostIPv4Manager

Manage IPv4 DHCP host records.

dhcphostipv6 cached property

dhcphostipv6: DhcpHostIPv6Manager

Manage IPv6 DHCP host records.

dhcphostipv6byipv4 cached property

dhcphostipv6byipv4: DhcpHostIPv6ByIPv4Manager

Manage IPv6 DHCP host records by IPv4 address.

hinfo cached property

hinfo: HInfoManager

Manage HINFO records.

host cached property

Manage hosts.

hostgroup cached property

hostgroup: HostGroupManager

Manage host groups.

ipaddress cached property

ipaddress: IPAddressManager

Manage IP addresses.

label cached property

label: LabelManager

Manage labels.

location cached property

location: LocationManager

Manage locations.

meta cached property

Access server metadata and health endpoints.

mx cached property

Manage MX records.

nameserver cached property

nameserver: NameServerManager

Manage nameservers.

naptr cached property

naptr: NAPTRManager

Manage NAPTR records.

network cached property

network: NetworkManager

Manage networks.

networkpolicy cached property

networkpolicy: NetworkPolicyManager

Manage network policies.

networkpolicyattribute cached property

networkpolicyattribute: NetworkPolicyAttributeManager

Manage network policy attributes.

permission cached property

permission: PermissionManager

Manage permissions.

policy cached property

policy: HostPolicyManagerNamespace

Manage host policy related resources.

ptroverride cached property

ptroverride: PTROverrideManager

Manage PTR overrides.

role cached property

Manage host policy roles.

srv cached property

Manage SRV records.

sshfp cached property

sshfp: SSHFPManager

Manage SSHFP records.

timeout property writable

timeout: float | None

Get the current timeout setting.

txt cached property

Manage TXT records.

zone cached property

Manage forward and reverse zones.

__del__

__del__() -> None

Cleanup on deletion.

__init__

__init__(
    url: str,
    domain: str | None = None,
    user: str | None = None,
    timeout: int | float | None = 60,
    cache: CacheConfig | bool = False,
    follow_redirects: bool = False,
    page_size: int | None = None,
    request_log_size: int | None = 100,
    event_log_size: int | None = 100,
    user_agent: str | None = None,
    history_size: int | None | UNSET = UNSET,
) -> None

Initialize the client.

caching

caching(enable: bool = True)

Context manager to temporarily enable or disable caching.

Parameters:

Name Type Description Default
enable bool

If True, enable caching within the context. If False, disable caching within the context.

True

Example:

>>> with client.caching(enable=True):
...     # caching is enabled here
...     pass
>>> with client.caching(enable=False):
...     # caching is disabled here
...     pass

clear_cache

clear_cache() -> int

Clear the client's GET response cache.

clear_client_history

clear_client_history() -> None

Clear the request/response log for this client.

delete

delete(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[True],
) -> Response | None
delete(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[False],
) -> Response
delete(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: bool,
) -> Response | None
delete(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
) -> Response
delete(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
    ok404: bool = False,
) -> Response | None

Make a DELETE request.

disable_cache

disable_cache(*, clear: bool = True) -> None

Disable caching of GET responses for this client.

Parameters:

Name Type Description Default
clear bool

If True, clear the existing cache data. If False, leave the cache data intact.

True

domain_override

domain_override(
    domain: str | None,
) -> Generator[None, None, None]

Temporarily override the hostname domain used by :meth:fqdn.

Parameters:

Name Type Description Default
domain str | None

The domain to use within the context.

required

Example:

>>> with client.domain_override("example.com"):
...     client.fqdn("web")  # → "web.example.com"

enable_cache

enable_cache(config: CacheConfig | None = None) -> None

Enable caching of GET responses for this client.

If a new config is provided, the cache is recreated with that config. Otherwise, just enables caching on the existing cache.

fqdn

fqdn(name: str) -> HostName

Normalise and expand a hostname using this client's configured domain.

Not technically a FQDN, since we don't include a trailing dot, but that's not a concept MREG operates on anyway.

get

get(
    path: str,
    *,
    params: QueryParams | None = ...,
    ok404: Literal[True],
) -> Response | None
get(
    path: str,
    *,
    params: QueryParams | None = ...,
    ok404: Literal[False],
) -> Response
get(
    path: str,
    *,
    params: QueryParams | None = ...,
    ok404: bool,
) -> Response | None
get(
    path: str, *, params: QueryParams | None = None
) -> Response
get(
    path: str,
    *,
    params: QueryParams | None = None,
    ok404: bool = False,
) -> Response | None

Make a standard get request.

get_cache_info

get_cache_info() -> CacheInfo | None

Get statistics about the client's cache.

Returns:

Type Description
CacheInfo | None

CacheInfo object or None if caching is disabled

get_client_history

get_client_history() -> RequestLog

Get the request/response log for this client.

Returns:

Type Description
RequestLog

RequestLog object containing the log of requests and responses

get_correlation_id

get_correlation_id() -> str

Get the current correlation ID.

Returns:

Type Description
str

Current correlation ID or empty string

get_count

get_count(path: str, *, strict: bool = False) -> int

Get the count of items from a list endpoint.

Warning

Returns the length of the results if the endpoint does not implement pagination.

Returns:

Type Description
int

The count of items.

get_first

get_first(
    path: str, params: QueryParams | None = None
) -> JsonMapping | None

Get the first item from a list endpoint.

get_item_by_key_value

get_item_by_key_value(
    path: str,
    search_field: str,
    search_value: str | int,
    ok404: bool = False,
) -> None | JsonMapping

Get an item by a key value pair.

Parameters:

Name Type Description Default
path str

The path to the API endpoint.

required
search_field str

The field to search for.

required
search_value str | int

The value to search for.

required
ok404 bool

Whether to allow 404 responses.

False

Returns:

Type Description
None | JsonMapping

A single dictionary, or None if no result was found and ok404 is True.

get_list

get_list(
    path: str,
    params: QueryParams | None = None,
    ok404: bool = False,
    limit: int | None = None,
) -> list[Json]

Make a get request that produces a list.

Iterates over paginated results and returns them as a list. If the total number of hits exceeds limit, the results are truncated to limit and a EventKind.TRUNCATION event is recorded on self.events.

Parameters:

Name Type Description Default
path str

The path to the API endpoint.

required
params QueryParams | None

The parameters to pass to the API endpoint.

None
ok404 bool

Whether to allow 404 responses.

False
limit int | None

The maximum number of hits to return. Results beyond this are dropped (and a truncation event recorded). Set to None for no limit.

None

Returns:

Type Description
list[Json]

A list of dictionaries.

get_list_in

get_list_in(
    path: str,
    search_field: str,
    search_values: list[int],
    ok404: bool = False,
) -> list[Json]

Get a list of items by a key value pair.

Parameters:

Name Type Description Default
path str

The path to the API endpoint.

required
search_field str

The field to search for.

required
search_values list[int]

The values to search for.

required
ok404 bool

Whether to allow 404 responses.

False

Returns:

Type Description
list[Json]

A list of dictionaries.

get_list_unique

get_list_unique(
    path: str,
    params: QueryParams | None = None,
    ok404: bool = False,
) -> None | JsonMapping

Do a get request that returns a single result from a search.

Parameters:

Name Type Description Default
path str

The path to the API endpoint.

required
params QueryParams | None

The parameters to pass to the API endpoint.

None
ok404 bool

Whether to allow 404 responses.

False

Returns:

Type Description
None | JsonMapping

A single dictionary, or None if no result was found and ok404 is True.

get_token

get_token() -> str | None

Get the current authorization token if set.

Returns:

Type Description
str | None

Token string or None if not authenticated

get_typed

get_typed(
    path: str,
    type_: type[T],
    params: QueryParams | None = None,
    limit: int | None = None,
) -> T

Fetch and deserialize JSON from an endpoint into a specific type.

This function is a wrapper over the get() function, adding the additional functionality of validating and converting the response data to the specified type.

Parameters:

Name Type Description Default
path str

The path to the API endpoint.

required
type_ type[T]

The type to which the response data should be deserialized.

required
params QueryParams | None

The parameters to pass to the API endpoint.

None
limit int | None

The maximum number of hits to allow for paginated responses.

None

Raises:

Type Description
ValidationError

If the response cannot be deserialized into the given type.

Returns:

Type Description
T

An instance of type_ populated with data from the response.

login

login(username: str, password: str) -> str

Authenticate with username and password.

Parameters:

Name Type Description Default
username str

MREG username

required
password str

MREG password

required

Raises:

Type Description
LoginFailedError

If authentication fails

Returns:

Type Description
str

The authentication token

logout

logout() -> None

Logout from MREG (invalidate token on server).

patch

patch(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[True],
) -> Response | None
patch(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[False],
) -> Response
patch(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: bool,
) -> Response | None
patch(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
) -> Response
patch(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
    ok404: bool = False,
) -> Response | None

Make a PATCH request.

post

post(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[True],
) -> Response | None
post(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: Literal[False],
) -> Response
post(
    path: str,
    *,
    json: Json | None = ...,
    params: QueryParams | None = ...,
    ok404: bool,
) -> Response | None
post(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
) -> Response
post(
    path: str,
    *,
    json: Json | None = None,
    params: QueryParams | None = None,
    ok404: bool = False,
) -> Response | None

Make a POST request.

request

request(
    method: HTTPMethod,
    path: str,
    *,
    params: QueryParams | None = None,
    ok404: bool = False,
    json: Json | None = None,
) -> Response | None

Make an HTTP request to the MREG API.

Parameters:

Name Type Description Default
method HTTPMethod

HTTP method

required
path str

API path (relative to base URL)

required
params QueryParams | None

Query parameters

None
ok404 bool

Whether to return None on 404 instead of raising

False
json Json | None

Request body data as a JSON-serializable value

None

Returns:

Type Description
Response | None

Response object or None if ok404=True and status is 404

Raises:

Type Description
APIError

If request fails

set_correlation_id

set_correlation_id(suffix: str) -> str

Set correlation ID for request tracking.

Parameters:

Name Type Description Default
suffix str

Human-readable suffix for the correlation ID

required

Returns:

Type Description
str

The generated correlation ID

set_token

set_token(token: str) -> None

Set the authorization token for API requests.

Parameters:

Name Type Description Default
token str

Bearer token for authentication

required

test_auth

test_auth() -> None

Test if the current authorization token is valid.

Does not handle connection errors.

Raises:

Type Description
APIError

If the authorization test fails

Returns:

Type Description
None

True if authorization is valid, False otherwise

unset_token

unset_token() -> None

Unset the current authorization token.