Mikrotik Api Examples [TESTED]

api('/ip/firewall/filter/set', '.id': '*1', 'comment': 'Updated by API' )

api = librouteros.connect(...)
for connection in api.path('/ip/firewall/connection'):
    print(connection['protocol'], connection['src-address'], '->', connection['dst-address'])
api.close()

The MikroTik API is the definition of a "mechanical" interface. It is not a modern, RESTful, JSON-formatted playground. It is a raw, direct pipe into the RouterOS kernel. Rating: 8/10 for utility, 5/10 for developer experience. mikrotik api examples

While it lacks the polish of Meraki or the standardization of NETCONF/YANG, it offers granular control that few other platforms can match. If you are willing to roll up your sleeves and write code, you can automate literally anything on a MikroTik router. api('/ip/firewall/filter/set', '


In this example, we'll create a new user using the Mikrotik API in PHP. api = librouteros

<?php
// Mikrotik device details
$device_ip = '192.168.1.1';
$username = 'admin';
$password = 'password';
// API endpoint
$api_url = "http://$device_ip/api/v1";
// Authenticate and create a new user
$auth = base64_encode("$username:$password");
$headers = array(
    'Authorization: Basic ' . $auth,
    'Content-Type: application/json'
);
$new_user = array(
    'username' => 'newuser',
    'password' => 'newpassword',
    'group' => 'admin'
);
$response = curl_init($api_url . '/user');
curl_setopt($response, CURLOPT_RETURNTRANSFER, true);
curl_setopt($response, CURLOPT_POST, true);
curl_setopt($response, CURLOPT_POSTFIELDS, json_encode($new_user));
curl_setopt($response, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($response);
curl_close($response);
if ($result) 
    echo 'User created successfully';
 else 
    echo 'Error creating user';

This code creates a new user with the username newuser, password newpassword, and group admin.

Scroll to Top