How to add DHCP client using Python RouterOS-api

Use the following Python code to add a new DHCP client on the bridge interface using the Python RouterOS-api package:

# Add a new DHCP client on bridge interface
print(f"Adding new DHCP client on bridge interface")
dhcp_client_resource = api.get_resource('/ip/dhcp-client')
try:
    dhcp_client_resource.add(interface='bridge', disabled='no')
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
    error_message = str(e)
    if 'dhcp-client on that interface already exists' in error_message:
        print("DHCP client already exists")
    else:
        raise e

For convenience, here’s this code as a function:


def add_dhcp_client(api, interface):
    """
    Add a new DHCP client on bridge interface.

    Parameters:
    - api (routeros_api.RouterOsApi): The RouterOS API object.
    - interface (str): The name of the bridge interface.

    Returns:
    - bool: True if the DHCP client was added successfully, False otherwise (if it already exists).

    Raises:
    - routeros_api.exceptions.RouterOsApiCommunicationError:
        If there is an error in the RouterOS API communication, except if the error is just
        that the DHCP client already exists (in that case, it returns False).
    """
    # Add a new DHCP client on bridge interface
    dhcp_client_resource = api.get_resource('/ip/dhcp-client')
    try:
        dhcp_client_resource.add(interface='bridge', disabled='no')
        return True
    except routeros_api.exceptions.RouterOsApiCommunicationError as e:
        error_message = str(e)
        if 'dhcp-client on that interface already exists' in error_message:
            print("DHCP client already exists")
        else:
            raise e
        return False

# Example usage
add_dhcp_client(api, 'bridge')

Full example

The following example works for me with a factory-configured MikroTik wAP-LTE kit.

#!/usr/bin/env python3
import routeros_api

connection = routeros_api.RouterOsApiPool(
    '192.168.88.1', username='admin', password='L9TYAUV7R8',
    plaintext_login=True
)
api = connection.get_api()

# Add a new DHCP client on bridge interface
print(f"Adding new DHCP client on bridge interface")
dhcp_client_resource = api.get_resource('/ip/dhcp-client')
try:
    dhcp_client_resource.add(interface='bridge', disabled='no')
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
    error_message = str(e)
    if 'dhcp-client on that interface already exists' in error_message:
        print("DHCP client already exists")
    else:
        raise e