Mikrotik Api Examples (AUTHENTIC ›)

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

<?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.

logs = api.path('log').select('time', 'topics', 'message')
for log in logs:
    if 'error' in log['topics'].lower():
        print(f"ERROR: log['time'] - log['message']")

| Action | API Path | Example | |--------|----------|---------| | Get interfaces | /interface/print | connection.path('interface').get() | | Add simple queue | /queue/simple/add | add(name='queue1', target='10.0.0.5', max_limit='2M/2M') | | Remove by ID | /ip/address/remove | .path('ip', 'address').remove('.id=*1') | | Set DNS server | /ip/dns/set | set(servers='8.8.8.8', allow_remote_requests='yes') |


def cleanup_expired_users(): users = hotspot.get() for user in users: if 'expires_after' in user and datetime.now() > datetime.strptime(user['expires_after'], '%Y-%m-%d %H:%M:%S'): hotspot.remove(id=user['id']) print(f"🗑 Removed expired user user['name']")

cleanup_expired_users()

connection.disconnect()


The MikroTik API is not for the "low-code" crowd. It is for the engineer who needs to automate the deployment of 500 routers, provision 10,000 HotSpot users, or sync dynamic DNS records across a WAN. mikrotik api examples

If you approach it expecting a RESTful experience, you will be frustrated. If you approach it as a developer-friendly version of the CLI, you will find it indispensable.

Who is this for?

Who is this NOT for?

The Power of MikroTik API: From Automation to Real-Time Monitoring

MikroTik’s Application Programmable Interface (API) is a potent tool for network administrators looking to move beyond the manual constraints of Winbox or the CLI. Whether you are using the classic RouterOS API or the newer REST API introduced in version 7, these tools allow you to build custom software that manages configurations and monitors traffic in real time.

Below are several compelling examples of how the MikroTik API is used to solve real-world networking challenges. 1. Automated Branch VPN Setup In this example, we'll create a new user

A common challenge for ISPs or large enterprises is managing numerous branch offices. Using a Python-based RouterOS API library, administrators can create scripts that automatically configure IPSec tunnels between headquarters and new branches.

Benefit: Reduces human error during setup and allows junior staff to deploy complex VPN configurations by simply entering source and destination networks. 2. Hardware-Based Traffic Dashboards

For a "heads-up" display of network health, developers have integrated MikroTik with microcontrollers like the

. By querying the REST API for interface statistics and CPU load, you can display live traffic graphs on a small TFT screen. Setup: The Go to product viewer dialog for this item.

connects via Wi-Fi, sends a GET request to the router, and parses the returned JSON data to refresh the display every few seconds. 3. Customer Hotspot Management

The API is frequently used to bridge the gap between MikroTik routers and web-based billing systems. This code creates a new user with the

Active User Tracking: Use the /ip/hotspot/active/print command via a PHP API class to see who is currently online.

Dynamic Walled Gardens: Automatically update "walled garden" lists (allowed websites for unauthenticated users) based on specific marketing campaigns or schedules.

User Information: Developers often query the /ip hotspot cookie menu to reliably retrieve the MAC address and login status of a specific device. 4. Enterprise Monitoring & Auditing

With the advent of RouterOS v7, the REST API allows for even more flexible interaction using standard tools like curl or Postman. REST API - RouterOS - MikroTik Documentation

In this example, we'll use Python to retrieve basic device information using the Mikrotik API.

import requests
# Mikrotik device details
device_ip = '192.168.1.1'
username = 'admin'
password = 'password'
# API endpoint
api_url = f'http://device_ip/api/v1'
# Authenticate and retrieve device information
auth = (username, password)
response = requests.get(f'api_url/system/info', auth=auth)
if response.status_code == 200:
    device_info = response.json()
    print(device_info)
else:
    print('Authentication failed')

This code retrieves the device's system information, including the model, serial number, and firmware version.