Mikrotik Api Examples [exclusive] Review

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

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.

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

MikroTik offers two primary ways to interact with its devices programmatically: the legacy binary API (for high-performance tasks) and the modern introduced in RouterOS v7. 1. Modern REST API (RouterOS v7+)

The REST API is the easiest to use as it works with standard HTTP tools like or Postman. Enabling the Service: /ip/service www-ssl disabled=no # Secure access via HTTPS /ip/service www disabled=no # Access via HTTP (v7.9+) Use code with caution. Copied to clipboard Example: Get System Resource Info curl -k -u admin:password

The MikroTik API allows you to build custom software to manage

devices by sending "sentences" that mirror the command-line interface (CLI). Modern RouterOS v7 also introduces a

for easier integration with web tools and standard HTTP libraries. Support Service 1. Enabling API Access

Before using either API, you must enable the service on your router: Legacy API /ip service set api disabled=no (Port 8728) /ip service set api-ssl disabled=no (Port 8729) /ip service set www-ssl disabled=no (Port 443) 2. Common API Examples

The API follows a specific sentence structure: command words (e.g., /ip/address/print ) followed by attribute words (e.g., =interface=ether1 Python (Legacy API)

Using a standard library or a simple socket-based client, you can automate tasks like IP management

# Conceptual example of sending a command to get all IP addresses /ip/address/print .proplist=address,interface Use code with caution. Copied to clipboard REST API (RouterOS v7+) The REST API uses standard HTTP methods ( ) and JSON. List Addresses (GET) curl -k -u admin:password https://192.168.88 Add an IP (POST)

curl -k -u admin:password -X POST https://192.168.88 -d '"address":"10.0.0.1/24", "interface":"ether1"' Remove an IP (DELETE) curl -k -u admin:password -X DELETE https://192.168.88 3. Popular API Libraries

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 mikrotik 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

Report: MikroTik API Implementation Examples and Guide

1. Introduction MikroTik's RouterOS is widely used in networking, and its API allows for powerful automation, monitoring, and management of routers. This report outlines the basics of connecting to the API and provides practical examples for common administrative tasks.

2. Connection Fundamentals The MikroTik API typically runs on TCP port 8728 (or 8729 for SSL). Unlike a standard shell, the API uses a specific sentence-based protocol.

  • Note: For production environments, it is highly recommended to use an existing library (such as librouteros for Python, RouterOSAPI for PHP, or node-mikrotik for NodeJS) rather than writing raw socket code.

3. Example Use Cases

Example 12: Manage PPPoE Secrets

ppp_secrets = api.path('ppp', 'secret')
# Add a PPPoE user
ppp_secrets.add(
    name='pppoe_user1',
    password='securepass',
    service='pppoe',
    profile='default-encryption',
    remote_address='10.10.10.5'
)
# Remove a user
ppp_secrets.remove('pppoe_user1')  # Either by name or .id

7. Advanced Operations

3. Monitoring Network Performance

In this example, we'll use Python to retrieve network performance data 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 network performance data
auth = (username, password)
response = requests.get(f'api_url/tool/monitor', auth=auth, stream=True)
if response.status_code == 200:
    for chunk in response.iter_lines():
        print(chunk)
else:
    print('Authentication failed')

This code retrieves real-time network performance data, including CPU usage, memory usage, and interface statistics.

Conclusion

In this blog post, we've explored Mikrotik API examples to help you get started with automating your network tasks. With the Mikrotik API, you can perform a wide range of tasks, from retrieving device information to monitoring network performance. By leveraging the power of automation, you can save time, reduce errors, and improve your overall network management efficiency.

Additional Resources

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

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. The Power of MikroTik API: From Automation to

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 offers two primary ways to interact with its devices programmatically: the traditional Binary API and the modern REST API introduced in RouterOS v7. 1. REST API (RouterOS v7+)

The REST API is resource-oriented and uses standard HTTP methods (GET, POST, PUT, DELETE) with JSON payloads.

Example: Get System IdentityYou can fetch router information using a simple GET request. curl -k -u admin:password -X GET https://192.168.88 Use code with caution. Copied to clipboard

Example: Add an IP AddressUse POST to create new configurations.

curl -k -u admin:password -X POST https://192.168.88 \ -H "content-type: application/json" \ -d '"address": "10.0.0.1/24", "interface": "ether1"' Use code with caution. Copied to clipboard

Example: Remove a ConfigurationUse DELETE with the specific resource's ID (e.g., *1). curl -k -u admin:password -X DELETE https://192.168.88 Use code with caution. Copied to clipboard 2. Traditional Binary API (v6 & v7)

The binary API uses a sentence-based protocol where each word is length-prefixed. It typically runs on port 8728 (plain) or 8729 (SSL).

Example: Login SequenceThe API requires a specific word sequence to authenticate. /login =name=admin =password=secret Use code with caution. Copied to clipboard

Example: Print IP AddressesCommands follow the CLI hierarchy but use slashes as separators. /ip/address/print Use code with caution. Copied to clipboard

Example: Complex QueriesTo filter results, you must use query words starting with ?. /ip/address/print ?interface=ether1 Use code with caution. Copied to clipboard 3. Popular Client Libraries

Most developers use specialized libraries to handle the underlying socket communication:

Python: Use the official Python3 Example from MikroTik or community libraries like RouterOS-api.

PHP: EvilFreelancer's PHP Client supports advanced queries and tags.

Java: The mikrotik-java client supports asynchronous commands and listeners. Essential Implementation Notes

Network Automation using Python on MikroTik (REST API Part 2)

Mastering the MikroTik API allows you to automate everything from small home networks to massive ISP infrastructures. Whether you use the classic binary API or the modern REST API introduced in RouterOS v7, programmatically managing your router opens up powerful automation possibilities. 🛠️ Getting Started: API Essentials

Before diving into code, ensure your router's API services are active.

API Services: Enable them via IP > Services in Winbox or the CLI. Binary API: Default port 8728 (unencrypted) or 8729 (SSL).

REST API: Uses standard HTTPS (port 443 or specified port) and provides responses in JSON.

Security: Always use SSL/HTTPS and restrict access by IP address in the service settings to prevent unauthorized access. 🐍 Python Example (Binary API)

The binary API uses a sentence-based protocol. Libraries like librouteros or pyros-api simplify this into standard Python calls.

from librouteros import connect # Connect to the router api = connect(host='192.168.88.1', username='admin', password='yourpassword') # Example: Print all IP addresses ip_addresses = api(cmd='/ip/address/print') for entry in ip_addresses: print(f"Interface: entry['interface'], Address: entry['address']") Use code with caution. Copied to clipboard Source: MikroTik MUM Presentation 🌐 REST API Example (RouterOS v7+)

The REST API is much more user-friendly for web developers and modern automation tools. You can use standard curl commands or any HTTP client. Fetch Interface Statistics: curl -k -u admin:password -X GET "https://192.168.88" Use code with caution. Copied to clipboard

Add a Firewall Rule:Note: In MikroTik's REST implementation, PUT is often used to create new records. Note: For production environments, it is highly recommended

curl -k -u admin:password -X PUT "https://192.168.88" \ -H "Content-Type: application/json" \ -d '"chain": "input", "src-address": "192.168.1.50", "action": "drop", "comment": "Block specific IP"' Use code with caution. Copied to clipboard Source: MikroTik REST API Documentation 🐘 PHP Example (Web Integration)

For building custom dashboards or management systems, PHP is a popular choice.

// Using the EvilFreelancer/routeros-api-php library $client = new \RouterOS\Client(['host' => '192.168.88.1', 'user' => 'admin', 'pass' => 'password']); // Simple query with 'where' condition $query = (new \RouterOS\Query('/ip/address/print')) ->where('interface', 'ether1'); $response = $client->query($query)->read(); print_r($response); Use code with caution. Copied to clipboard Source: EvilFreelancer/routeros-api-php (GitHub) 💡 Pro Tips for Automation REST API - RouterOS - MikroTik Documentation

The MikroTik RouterOS API is a powerful tool for network administrators who need to go beyond manual configuration. It allows for seamless automation, custom monitoring, and the integration of MikroTik hardware into larger software ecosystems. By using the API, you can treat your router as a programmable object rather than just a standalone appliance.

Here are three common ways to use the MikroTik API, ranging from basic monitoring to advanced automation. 1. Real-Time Resource Monitoring (Python)

One of the most common uses for the API is fetching system health data to feed into a dashboard or an alerting system. Using a library like RouterOS-api , you can quickly pull CPU and memory stats. routeros_api connection = routeros_api.RouterOsApiPool( 192.168.88.1 , username= , password= = connection.get_api() # Get system resources = api.get_resource( /system/resource = resource.get()

print( Free Memory: {int(data[ free-memory )

connection.disconnect() Use code with caution. Copied to clipboard 2. Dynamic User Management (PHP)

For ISPs or managed service providers, the API is essential for automating user access. This example shows how you might programmatically add a new user to a Hotspot or a PPPoE service via a web portal. // Using a standard PHP client library '192.168.88.1' 'password' ]);

$client->query([ '/ip/hotspot/user/add' '=name=new_customer' '=password=securepass123' '=profile=default' '=comment=Added via Web Portal' ])->read(); Use code with caution. Copied to clipboard 3. Bulk Configuration Updates (Node.js)

If you manage dozens of routers, logging into each one to update a firewall rule is inefficient. The API allows you to push configuration changes across your entire fleet simultaneously. javascript RouterOSClient = 'routeros-client' ).RouterOSClient; updateFirewall() { RouterOSClient( host: '192.168.88.1' , password: 'password' api.connect(); // Block a specific IP address conn.write( '/ip/firewall/filter/add' '=chain=forward' '=action=drop' '=src-address=10.0.0.50' '=comment=Automated block' ]);

conn.close();

Use code with caution. Copied to clipboard Why use the API instead of SSH/CLI? While SSH scripting is popular, the API provides structured data

Here’s a practical guide to working with the MikroTik API, including common examples in Python and bash. The API uses plain text commands over TCP port 8728 (or 8729 for SSL).


Example 3: Configure a VLAN

Using the Mikrotik API, you can configure a VLAN as follows:

import mikrotik
# Connect to the device
api = mikrotik.Mikrotik('192.168.1.1', 'admin', 'password')
# Create a new VLAN
vlan = api.get_resource('/interface/vlan').add(
    name='vlan10',
    vlan_id=10,
    interface='ether1'
)
# Set IP address for the VLAN
ip = api.get_resource('/ip/address').add(
    address='192.168.10.1/24',
    interface='vlan10'
)

This code creates a new VLAN with the name vlan10, VLAN ID 10, and interface ether1. It then sets the IP address for the VLAN to 192.168.10.1/24.

Common Mikrotik API Commands

Here are some common Mikrotik API commands:

  • get_resource(): Retrieves a resource, such as a configuration item or a monitoring value.
  • add(): Creates a new resource, such as a user or a VLAN.
  • set(): Updates an existing resource.
  • remove(): Deletes a resource.

Mikrotik API Libraries and Tools

There are several libraries and tools available that support the Mikrotik API, including:

  • mikrotik-api Python library
  • Winbox utility
  • Mikrotik_API Perl library
  • pyMikrotik Python library

Conclusion

In this article, we explored Mikrotik API examples and provided a comprehensive guide on how to get started with Mikrotik API. The Mikrotik API offers a powerful way to interact with Mikrotik devices, automate tasks, and integrate with other systems. With the right libraries and tools, developers can create custom applications and scripts that leverage the Mikrotik API.

Additional Resources

For more information on Mikrotik API, please refer to:

By following this guide and experimenting with Mikrotik API examples, you can unlock the full potential of your Mikrotik devices and take your network automation to the next level.


🔧 Feature: Dynamic Guest Wi-Fi with Voucher System