- OpenWrt Modular API Server
A highly modular and extensible REST API server for OpenWrt routers, built with the Mongoose embedded web server library.
- Modular Architecture: Easy to add new endpoints and functionality
- Comprehensive System Info: Access system status, memory, CPU, and network information
- Network Management: Monitor WAN/LAN status, DHCP leases, and routing
- Wireless Control: View WiFi configuration, scan networks, and manage connections
- Extensible Design: Simple framework for adding custom API endpoints
- JSON Responses: All responses in standardized JSON format
- Built-in Documentation: Self-documenting API with endpoint listings
After installation, the API server runs on port 9000. Access the documentation at:
http://your-router-ip:9000/api
GET /api- API documentation and endpoint listingGET /api/help- Same as above
GET /api/status- API server statusGET /api/health- System health checkGET /api/version- Version information
GET /api/system/info- Comprehensive system informationGET /api/system/uptime- System uptimeGET /api/system/memory- Memory usageGET /api/system/load- System load averageGET /api/system/datetime- Current date and timePOST /api/system/reboot- Schedule system reboot
GET /api/network/interfaces- Network interface listGET /api/network/routes- Routing tableGET /api/network/wan- WAN interface statusGET /api/network/lan- LAN interface statusGET /api/network/dhcp/leases- DHCP lease informationGET /api/network/ping- Connectivity test
GET /api/wireless/status- Wireless interface statusGET /api/wireless/scan- Scan for WiFi networksGET /api/wireless/config- Current WiFi configurationGET /api/wireless/clients- Connected client countPOST /api/wireless/restart- Restart wireless interface
-
Create Endpoint Module:
./scripts/generate_endpoint.sh your_module_name
-
Update Headers: Add function declaration to
api/api_manager.h:void register_your_module_endpoints(api_manager_t *manager);
-
Register in Main: Add to
main.cininitialize_api_endpoints():register_your_module_endpoints(&api_manager);
-
Update Makefile: Add source file to
SOURCESlist:$(PKG_BUILD_DIR)/api/endpoints/your_module.c \
#include "../api_manager.h"
#include "../helpers/response.h"
static void handle_custom_endpoint(struct mg_connection *c, struct mg_http_message *hm) {
// Simple success response
send_success_response(c, "Custom endpoint works", NULL);
// JSON object response
const char *kvp[] = {"key1", "value1", "key2", "value2"};
char *json = build_json_object(kvp, 4);
send_json_response(c, 200, json);
free_json_string(json);
// Error response
send_error_response(c, 400, "Bad Request", "Invalid parameters");
}send_json_response(c, status, json_data)send_success_response(c, message, data)send_error_response(c, status, error, message)send_data_response(c, key, value)
build_json_object(key_value_pairs, count)build_json_array(items, count)free_json_string(json_str)
get_system_uptime()get_system_load()get_memory_info()get_cpu_info()get_hostname()run_command(command)get_openwrt_version()get_uci_config(config_name)
curl http://your-router-ip:9000/api/monitoring/processesResponse Example:
{
"success": true,
"processes": [
{
"rank": 1,
"pid": 1234,
"name": "uhttpd",
"rss_kb": 2048,
"rss_mb": 2.0
},
{
"rank": 2,
"pid": 5678,
"name": "kernel",
"rss_kb": 1536,
"rss_mb": 1.5
}
],
"summary": {
"total_processes": 45,
"total_ram_kb": 12345,
"total_ram_mb": 12.05,
"highest_process": "uhttpd",
"highest_ram_kb": 2048,
"highest_ram_mb": 2.0
}
}# Get top 10 processes
curl http://your-router-ip:9000/api/monitoring/processes/top/10
# Get top 5 processes
curl http://your-router-ip:9000/api/monitoring/processes/top/5Response Example:
{
"success": true,
"limit": 10,
"processes": [
{
"rank": 1,
"pid": 1234,
"name": "uhttpd",
"rss_kb": 2048,
"rss_mb": 2.0
}
]
}curl http://your-router-ip:9000/api/monitoring/memory/summaryResponse Example:
{
"success": true,
"memory": {
"total_kb": 131072,
"total_mb": 128.0,
"free_kb": 45678,
"free_mb": 44.61,
"used_kb": 85394,
"used_mb": 83.39,
"available_kb": 50000,
"available_mb": 48.83,
"buffers_kb": 2048,
"cached_kb": 8192,
"usage_percent": 65.15
}
}curl http://your-router-ip:9000/api/monitoring/system/statsResponse Example:
{
"success": true,
"system_stats": {
"uptime_seconds": "12345.67",
"load_average": "0.25 0.30 0.28",
"total_processes": 45,
"total_process_ram_kb": 12345,
"total_process_ram_mb": 12.05,
"top_process": {
"name": "uhttpd",
"pid": 1234,
"ram_kb": 2048,
"ram_mb": 2.0
}
}
}You can now easily create web dashboards that consume this data:
// Fetch top 10 processes
fetch("/api/monitoring/processes/top/10")
.then((response) => response.json())
.then((data) => {
console.log("Top process:", data.processes[0].name);
console.log("RAM usage:", data.processes[0].rss_mb + " MB");
});
// Fetch memory summary
fetch("/api/monitoring/memory/summary")
.then((response) => response.json())
.then((data) => {
console.log("Memory usage:", data.memory.usage_percent + "%");
});The monitoring module maintains all the functionality of your original script while providing it through a clean REST API interface!
The API manager supports:
METHOD_GETMETHOD_POSTMETHOD_PUTMETHOD_DELETEMETHOD_PATCH
All endpoints should handle errors gracefully:
static void handle_example(struct mg_connection *c, struct mg_http_message *hm) {
if (!file_exists("/some/required/file")) {
send_error_response(c, 404, "Not Found", "Required file not found");
return;
}
char *data = read_file("/some/file");
if (!data) {
send_error_response(c, 500, "Internal Server Error", "Failed to read file");
return;
}
send_data_response(c, "file_content", data);
}# Start service
/etc/init.d/api_c start
# Stop service
/etc/init.d/api_c stop
# Restart service
/etc/init.d/api_c restart
# Check status
/etc/init.d/api_c statusEdit /etc/config/api_c to change the port:
config api_c 'main'
option port '9000'
option enabled '1'
- The API currently runs without authentication
- Be careful with system modification endpoints (reboot, restart services)
- Consider implementing rate limiting for production use
- Network access should be restricted to trusted networks
-
Service won't start:
logread | grep api_c -
Compilation errors:
- Check all source files are included in Makefile
- Verify function declarations in headers match implementations
-
404 errors:
- Check route registration in module functions
- Verify endpoint module is registered in main.c
Enable verbose logging by modifying the service startup script or running manually:
/usr/bin/api_c 9000When adding new features:
- Follow the modular structure
- Use the provided helper functions
- Add comprehensive error handling
- Update this documentation
- Test all endpoints thoroughly
This project is part of the OpenWrt ecosystem and follows OpenWrt licensing.