import httpx import json class RadioAPIClient: """ A client wrapper for interacting with the Radio App Server API. Uses httpx for asynchronous HTTP requests. """ def __init__(self, base_url="http://localhost:5000"): """ Initializes the API client. Args: base_url (str): The base URL of the server's API (default is http://localhost:5000). """ self.base_url = base_url # Use an AsyncClient for making asynchronous requests self._client = httpx.AsyncClient() async def __aenter__(self): """Allows using the client with async with.""" return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Ensures the client is closed when exiting async with.""" await self.close() async def close(self): """Closes the underlying HTTP client.""" await self._client.close() async def _request(self, method, endpoint, **kwargs): """ Helper method to make an asynchronous HTTP request. Args: method (str): The HTTP method (e.g., 'GET', 'POST'). endpoint (str): The API endpoint path (e.g., '/channels'). **kwargs: Additional arguments for httpx.AsyncClient.request. Returns: dict: The JSON response from the API. Raises: httpx.HTTPStatusError: If the request returns a non-2xx status code. httpx.RequestError: For other request-related errors. """ url = f"{self.base_url}{endpoint}" try: response = await self._client.request(method, url, **kwargs) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) return response.json() except httpx.HTTPStatusError as e: print(f"HTTP error occurred: {e}") # You might want to return the error response body or raise the exception raise except httpx.RequestError as e: print(f"An error occurred while requesting {e.request.url!r}: {e}") raise async def get_channels(self): """ Retrieves a summary list of all available radio channels. Returns: list: A list of channel summaries (e.g., [{"id": "channel_1", "name": "..."}]). """ print(f"Fetching channels from {self.base_url}/channels") return await self._request("GET", "/channels") async def get_channel_details(self, channel_id: str): """ Retrieves detailed information for a specific channel. Args: channel_id (str): The unique ID of the channel. Returns: dict: The channel details. Raises: httpx.HTTPStatusError: If the channel is not found (404). """ print(f"Fetching details for channel: {channel_id} from {self.base_url}/channels/{channel_id}") return await self._request("GET", f"/channels/{channel_id}") async def list_clients(self): """ Retrieves a list of currently connected client IDs. Returns: list: A list of client IDs (strings). """ print(f"Fetching connected clients from {self.base_url}/clients") return await self._request("GET", "/clients") async def send_command(self, client_id: str, command_name: str, args: list = None): """ Sends a command to a specific client via the server's API. Args: client_id (str): The ID of the target client. command_name (str): The name of the command to execute on the client. args (list, optional): A list of arguments for the command. Defaults to None. Returns: dict: The API response indicating the command status. """ if args is None: args = [] print(f"Sending command '{command_name}' to client {client_id} with args {args} via API") return await self._request( "POST", f"/command/{client_id}/{command_name}", json={"args": args} # API expects args in a JSON body ) # --- Example Usage --- async def example_api_usage(): """Demonstrates how to use the RadioAPIClient.""" # You can specify a different base_url if your server is elsewhere async with RadioAPIClient("http://localhost:5000") as api_client: print("\n--- Getting Channels ---") try: channels_summary = await api_client.get_channels() print("Channels Summary:", channels_summary) except Exception as e: print(f"Error getting channels: {e}") print("\n--- Getting Channel Details (channel_1) ---") try: channel_details = await api_client.get_channel_details("channel_1") print("Channel 1 Details:", channel_details) except Exception as e: print(f"Error getting channel details: {e}") print("\n--- Getting Channel Details (non-existent) ---") try: non_existent_channel = await api_client.get_channel_details("non_existent_channel") print("Non-existent Channel Details:", non_existent_channel) # This should not print except httpx.HTTPStatusError as e: print(f"Caught expected error for non-existent channel: {e.response.status_code} - {e.response.json()}") except Exception as e: print(f"Error getting non-existent channel details: {e}") print("\n--- Listing Connected Clients ---") try: connected_clients = await api_client.list_clients() print("Connected Clients:", connected_clients) # --- Sending a Command (Requires a client to be running with a matching ID) --- if connected_clients: target_client_id = connected_clients[0] # Send to the first connected client print(f"\n--- Sending 'print_message' command to {target_client_id} ---") try: command_response = await api_client.send_command( target_client_id, "print_message", ["Hello from the API wrapper!"] ) print("Command Response:", command_response) except Exception as e: print(f"Error sending command: {e}") print(f"\n--- Sending 'run_task' command to {target_client_id} ---") try: command_response = await api_client.send_command( target_client_id, "run_task", ["api_task_1", 3] # task_id, duration_seconds ) print("Command Response:", command_response) except Exception as e: print(f"Error sending command: {e}") else: print("No clients connected to send commands to.") except Exception as e: print(f"Error listing clients or sending commands: {e}") if __name__ == "__main__": # To run this example: # 1. Ensure the server (server.py) is running. # 2. Ensure at least one client (client.py) is running. # 3. Run this script: python api_client.py asyncio.run(example_api_usage())