Api Examples | Mikrotik
For network engineers and system administrators, managing a fleet of MikroTik routers (RouterOS) via the graphical WinBox or WebFig interface is efficient for one-off tasks. However, when you need to provision 100 routers, dynamically update firewall filters based on an external threat feed, or automate bandwidth changes based on the time of day, the command-line interface (CLI) and GUI fall short.
Enter the MikroTik API.
The MikroTik API (based on a plain-text, TCP-based protocol) allows you to execute commands, configure settings, and retrieve data programmatically using scripts, Python, Go, or PHP. This article provides a deep dive into practical, real-world MikroTik API examples.
Limit a specific IP to 5Mbps download / 2Mbps upload.
queue = api.path('queue', 'simple').add(
name='customer-001',
target='192.168.88.100/32',
max_limit='5M/2M', # upload/download
comment='API traffic limit'
)
try:
result = api('/ip/address/add',
'address': '192.168.100.1/24',
'interface': 'ether1'
)
except librouteros.exceptions.TrapError as e:
print(f"API error: e")
# e.code, e.message
except ConnectionError:
print("Cannot connect to router")
# Add a simple queue
api('/queue/simple/add',
'name': 'user1',
'target': '192.168.88.100/32',
'max-limit': '5M/5M',
'parent': 'none'
)
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. mikrotik api examples
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
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) For network engineers and system administrators, managing a
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' ]);
the API provides structured data
$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