from fastapi import APIRouter, status from fastapi.responses import JSONResponse, HTMLResponse import platform import psutil # Initialize the router for this feature router = APIRouter( prefix="/server-status", tags=["Server Info"], responses={404: {"description": "Not found"}}, ) # ========================== # 📊 API Endpoint # ========================== @router.get( "/full-info", summary="Get complete server/PC status and information", status_code=status.HTTP_200_OK ) def get_server_status(): """ Retrieves detailed hardware and software status of the server. """ # --- System Information --- system_info = { "system": platform.system(), "node_name": platform.node(), "release": platform.release(), "version": platform.version(), "machine": platform.machine(), "processor": platform.processor(), } # --- CPU Information --- # Note: cpu_percent(interval=None) is non-blocking but requires a previous call # or it returns 0.0 on first call. For an API, interval=0.1 is a good compromise. freq = psutil.cpu_freq() cpu_info = { "physical_cores": psutil.cpu_count(logical=False), "total_cores": psutil.cpu_count(logical=True), "cpu_usage_percent": psutil.cpu_percent(interval=0.1), "cpu_frequency_mhz": f"{freq.current:.2f}" if freq else "N/A", } # --- Memory Information (RAM) --- virtual_memory = psutil.virtual_memory() memory_info = { "total_gb": f"{virtual_memory.total / (1024**3):.2f}", "available_gb": f"{virtual_memory.available / (1024**3):.2f}", "used_gb": f"{virtual_memory.used / (1024**3):.2f}", "usage_percent": virtual_memory.percent, } # --- Disk Usage Information (Root partition) --- try: disk_usage = psutil.disk_usage('/') disk_info = { "total_gb": f"{disk_usage.total / (1024**3):.2f}", "used_gb": f"{disk_usage.used / (1024**3):.2f}", "free_gb": f"{disk_usage.free / (1024**3):.2f}", "usage_percent": disk_usage.percent, } except Exception: disk_info = {"error": "Could not read disk usage"} # --- Network Information (Simple) --- net_io = psutil.net_io_counters() network_info = { "bytes_sent_mb": f"{net_io.bytes_sent / (1024**2):.2f}", "bytes_recv_mb": f"{net_io.bytes_recv / (1024**2):.2f}", } response_data = { "system_information": system_info, "cpu_status": cpu_info, "memory_status": memory_info, "disk_status": disk_info, "network_io": network_info, } return JSONResponse(content=response_data, status_code=status.HTTP_200_OK) # ========================== # 🖥️ Dashboard UI Endpoint # ========================== @router.get("/ui", response_class=HTMLResponse) async def server_status_ui(): html_content = """ Server Monitor | by Sam
CPU Usage -- Cores
0%
Freq: -- MHz
Memory (RAM)
0%
Used: -- / -- GB
Disk (Root)
0%
Free: -- GB
Network I/O
  • ⬇️ Received -- MB
  • ⬆️ Sent -- MB
  • System Information
    """ return html_content