Mikrotik Api Examples «2025»

MikroTik offers two primary ways to interact with its devices programmatically: the traditional Binary API (fast, low-level) and the newer REST API introduced in RouterOS v7 (web-friendly, JSON-based). 1. REST API Examples (RouterOS v7+)

The REST API is the modern choice for web developers. It uses standard HTTP methods and JSON.

Fetching Data (GET)To get all IP addresses, you can send a GET request to the /rest/ip/address endpoint.

Creating a New Interface (POST)Use the POST method to add configurations. For example, adding a VLAN:

POST https://router/rest/interface/vlan "name": "vlan10", "vlan-id": 10, "interface": "ether1" Use code with caution. Copied to clipboard Source: MikroTik REST API Documentation

Updating Configurations (PATCH/PUT)To change an existing item, such as an interface name, use a PATCH request targeting the specific resource. 2. Binary API Examples

The legacy binary API is more efficient for real-time monitoring and high-frequency data exchange because it uses a custom socket-based protocol.

Python Example using librouterosThis library simplifies the low-level byte encoding.

from librouteros import connect # Connect to the router api = connect(username="admin", password="password", host="192.168.88.1") # Run a command to print all IP addresses ip_info = api(cmd="/ip/address/print") print(ip_info) Use code with caution. Copied to clipboard Source: MikroTik Automation Presentation

Manual Sentence StructureAt a low level, commands are sent as "sentences" of words. A login command looks like this:/login=name=admin=password=secret. 3. Practical Automation Use Cases

The API is commonly used for large-scale network management: MikroTik Scripting: Lesson 1 - Development environment mikrotik api examples

Mastering the MikroTik API: Practical Examples for Network Automation

MikroTik’s RouterOS is a powerhouse for networking, but managing hundreds of devices via WinBox or CLI is a recipe for burnout. The MikroTik API is the solution, allowing you to automate configuration, monitor traffic, and build custom dashboards.

Below is a comprehensive guide with real-world MikroTik API examples using Python and RouterOS commands. 1. Enabling the API on RouterOS

Before running any scripts, you must enable the API service on your MikroTik router. By default, the API uses port 8728 (unencrypted) or 8729 (SSL).

# Enable standard API /ip service set api disabled=no port=8728 # Enable API over SSL (Recommended) /ip service set api-ssl disabled=no port=8729 Use code with caution.

Pro Tip: Use /ip service set api address=192.168.88.0/24 to restrict API access to your management subnet. 2. Python API Example: Getting System Resource

The most popular way to interact with the API is via Python. We’ll use the LibRouteros library, but the logic applies to most wrappers. Installation pip install librouteros Use code with caution. The Script: Fetching CPU and Uptime

from librouteros import connect def get_router_stats(host, username, password): # Connect to the router api = connect(host=host, username=username, password=password) # Query the /system/resource path resource = api.path('/system/resource') stats = list(resource.select('cpu-load', 'uptime', 'board-name')) for item in stats: print(f"Device: item['board-name']") print(f"CPU Load: item['cpu-load']%") print(f"Uptime: item['uptime']") get_router_stats('192.168.88.1', 'admin', 'your_password') Use code with caution. 3. Advanced Example: Automating IP Whitelisting

A common use case for the API is dynamically updating address lists for security. Python Example: Adding an IP to a Firewall List

def add_to_whitelist(api, ip_address): firewall_list = api.path('/ip/firewall/address-list') firewall_list.add(list='Authorized_Users', address=ip_address, comment='Added via API') print(f"IP ip_address added to whitelist.") Use code with caution. 4. PHP API Example: Web Dashboard Integration MikroTik offers two primary ways to interact with

If you are building a web-based ISP portal, PHP is often the go-to. Using the RouterOS-PHP class:

use RouterOS\Client; use RouterOS\Query; $client = new Client([ 'host' => '192.168.88.1', 'user' => 'admin', 'pass' => 'password' ]); // Get all active wireless registrations $query = new Query('/interface/wireless/registration-table/print'); $responses = $client->query($query)->read(); print_r($responses); Use code with caution. 5. Useful API Paths for Automation

To build your own scripts, you need to know where the data lives. Here are the most used paths: Monitor Traffic /interface/monitor-traffic Manage Users /tool/user-manager/user DHCP Leases /ip/dhcp-server/lease Hotspot Active /ip/hotspot/active Reboot Router /system/reboot 6. Best Practices for MikroTik API

Use API-SSL: Never send credentials in plain text over the internet.

Create a Limited User: Don't use the 'admin' account. Create a specific user with only api and read (or write) permissions.

Handle Timeouts: Network glitches happen. Always wrap your connection logic in try/except blocks to prevent script crashes.

Batch Processing: If updating 1,000 queues, use the API's ability to handle multiple commands to avoid overwhelming the CPU. Conclusion

The MikroTik API transforms a simple router into a programmable network node. Whether you are building a custom billing system or an automated failover script, these examples provide the foundation to stop configuring manually and start scaling.

Mikrotik API Examples: Unlocking the Power of Automation

As a network administrator, managing and automating network tasks is crucial for efficiency and scalability. Mikrotik, a popular networking equipment manufacturer, provides a robust API (Application Programming Interface) that allows developers to interact with their devices programmatically. In this blog post, we'll explore Mikrotik API examples to help you get started with automating your network tasks. The Mikrotik API uses a simple, text-based protocol

What is Mikrotik API?

The Mikrotik API is a powerful tool that enables developers to access and manage Mikrotik devices remotely. It allows you to perform various tasks, such as:

The Mikrotik API uses a simple, text-based protocol that can be easily integrated with various programming languages, including Python, PHP, and Java.

Getting Started with Mikrotik API

Before diving into the examples, make sure you have:

  1. A Mikrotik device (e.g., RouterBOARD, Cloud Core Router)
  2. A computer with a programming language of your choice (e.g., Python, PHP)
  3. The Mikrotik API package installed on your device (usually comes pre-installed)

Mikrotik API Examples

Usage

voucher = generate_voucher() create_voucher_user(voucher, minutes_valid=120)

2. Creating a New User

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.

1. Prerequisites: Enabling the API on RouterOS

Before any code runs, ensure the API service is active on your MikroTik router.

/ip service enable api
/ip service set api port=8728  # Default port, change for security
/ip service set api address=192.168.88.0/24  # Restrict access

For encrypted communication (recommended over the internet), use API-SSL on port 8729.

/ip service enable api-ssl

4. Advanced Examples