Mikrotik Api Examples !!link!! -
Reviewing MikroTik API examples reveals a shift from a complex, proprietary protocol to a modern REST API introduced in RouterOS v7. While the older "binary" API is still supported for its performance, the REST API is now the preferred entry point for most developers due to its use of standard JSON and HTTP methods. 1. Modern REST API (RouterOS v7+)
The REST API is highly rated for its simplicity, as it eliminates the need for specialized client libraries for many tasks.
Key Benefit: You can use standard tools like curl, Postman, or any language with an HTTP library.
Syntax: It maps directly to CLI commands. For example, /ip/address/print in the CLI becomes a GET request to /rest/ip/address.
Capabilities: Supports standard GET (read), PATCH (update), PUT (create), and DELETE (remove) methods. mikrotik api examples
Limitations: Users have noted that some advanced filtering (using the .query syntax) can be "tricky" compared to standard REST implementations. 2. Legacy "Binary" API
This is the original low-level socket-based communication method. API - RouterOS - MikroTik Documentation - Support Service
Here’s a real-world feature you could build using the MikroTik API, complete with example code.
1. Prerequisites: Enabling the API on RouterOS
Before any code runs, ensure the API service is active on your MikroTik router. Reviewing MikroTik API examples reveals a shift from
/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
Login
s.send(b'/login\r\n') print(s.recv(4096).decode())
Send command
s.send(b'/interface/print\r\n') response = s.recv(4096).decode() print(response) s.close()
Note: The raw API requires handling of trap messages and multi-line responses. Better to use
librouterosormikrotik-apilibraries. Add static DHCP lease api('/ip/dhcp-server/lease/add'
Add static DHCP lease
api('/ip/dhcp-server/lease/add', 'address': '192.168.88.50', 'mac-address': '00:11:22:33:44:55', 'server': 'dhcp1', 'comment': 'Printer' )
Optional: remove expired users automatically
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()
Create hotspot user with expiration
def create_voucher_user(voucher_code, minutes_valid=60, profile="default"): hotspot = api.get_resource('/ip/hotspot/user') expiry = (datetime.now() + timedelta(minutes=minutes_valid)).strftime('%Y-%m-%d %H:%M:%S')
hotspot.add(
name=voucher_code,
password=voucher_code,
profile=profile,
limit_uptime=f"minutes_validm",
expires_after=expiry
)
print(f"✅ Voucher voucher_code created – valid for minutes_valid min")
