Build a REST API client CLI with click. Implement output formatting with a --format flag allowing json, yaml, or pretty-printed ASCII table output using tabulate.
Assistant
Implementing CLI REST client with output formatting
Planning a Python CLI using click to call REST APIs via GET, supporting output formatting through a --format flag with json, yaml, or pretty-printed ASCII tables (via tabulate), including robust type handling and error fallback.
Below is a minimal, fully working example of a REST API client CLI built with click. It supports a global --format flag that can output data as json, yaml, or a pretty-printed ASCII table (via tabulate).
python
#!/usr/bin/env python
"""
Example REST API client CLI with output formatting.
Install deps:
pip install click requests pyyaml tabulate
"""
import json
import sys
from typing import Any, Dict, List, Union
import click
import requests
import yaml
from tabulate import tabulate
# ------------------------------------------------------------------------------
# Formatting Helpers
# ------------------------------------------------------------------------------
def render_table(data: Any) -> str:
"""
Produce a table string from common data structures:
- list[dict]: keys become columns
- dict: key/value pairs become two-column rows
- list[...] or tuple[...]: enumerated rows
"""
if isinstance(data, list):
if not data:
return "<empty list>"
if isinstance(data[0], dict):
# list of dicts -> use keys as headers
return tabulate(data, headers="keys", tablefmt="github")
else:
# list of scalars -> enumerated rows
rows = [(idx + 1, val) for idx, val in enumerate(data)]
return tabulate(rows, headers=["#", "value"], tablefmt="github")
if isinstance(data, dict):
# dict -> key/value rows
rows = [(k, v) for k, v in data.items()]
return tabulate(rows, headers=["key", "value"], tablefmt="github")
# Fallback for other simple types
return str(data)
def format_output(data: Any, fmt: str) -> str:
fmt = fmt.lower()
if fmt == "json":
return json.dumps(data, indent=2, ensure_ascii=False)
elif fmt == "yaml":
# sort_keys=False preserves order for Python 3.7+
return yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
elif fmt == "table":
return render_table(data)
else:
raise ValueError(f"Unknown format: {fmt}")
# ------------------------------------------------------------------------------
# Click CLI
# ------------------------------------------------------------------------------
@click.group()
@click.option(
"--base-url",
envvar="API_BASE_URL",
help="Base URL for API (e.g. https://api.example.com)",
required=True,
)
@click.option(
"--token",
envvar="API_TOKEN",
help="Bearer token for authentication (optional)",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["json", "yaml", "table"], case_sensitive=False),
default="json",
show_default=True,
help="Output format",
)
@click.pass_context
def cli(ctx: click.Context, base_url: str, token: str, output_format: str):
"""
A simple REST API client. Example:
./client.py get /v1/items --format table
"""
ctx.ensure_object(dict)
ctx.obj["BASE_URL"] = base_url.rstrip("/")
ctx.obj["TOKEN"] = token
ctx.obj["FORMAT"] = output_format.lower()
def _request(
method: str,
url: str,
token: str = None,
json_body: Any = None,
) -> requests.Response:
headers = {"Accept": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
resp = requests.request(method, url, headers=headers, json=json_body)
try:
resp.raise_for_status()
except requests.HTTPError as e:
# Print error details, then re-raise
click.echo(f"HTTP error: {e}", err=True)
# Attempt to show server message if JSON
try:
msg = resp.json()
click.echo(msg, err=True)
except Exception:
pass
sys.exit(1)
return resp
def _print_response(resp: requests.Response, fmt: str):
# If content-type is JSON, parse; otherwise print text
ctype = resp.headers.get("Content-Type", "")
if "application/json" in ctype.lower():
data = resp.json()
else:
# Fallback to text if not JSON
data = resp.text
out = format_output(data, fmt)
click.echo(out)
@cli.command()
@click.argument("path", metavar="PATH", required=True)
@click.pass_context
def get(ctx: click.Context, path: str):
"""
Perform a GET request to the given PATH (relative to --base-url).
"""
base_url = ctx.obj["BASE_URL"]
token = ctx.obj["TOKEN"]
fmt = ctx.obj["FORMAT"]
url = f"{base_url}/{path.lstrip('/')}"
resp = _request("GET", url, token=token)
_print_response(resp, fmt)
@cli.command()
@click.argument("path", metavar="PATH", required=True)
@click.option(
"--data",
"json_data",
type=str,
help="JSON string to send as POST body, e.g. '{\"name\":\"foo\"}'",
)
@click.pass_context
def post(ctx: click.Context, path: str, json_data: str):
"""
Perform a POST request to the given PATH (relative to --base-url).
"""
base_url = ctx.obj["BASE_URL"]
token = ctx.obj["TOKEN"]
fmt = ctx.obj["FORMAT"]
url = f"{base_url}/{path.lstrip('/')}"
body = None
if json_data:
body = json.loads(json_data)
resp = _request("POST", url, token=token, json_body=body)
_print_response(resp, fmt)
if __name__ == "__main__":
cli()
Usage Examples
bash
# Base URL via env var for convenience
export API_BASE_URL=https://api.example.com
# Get items in JSON
./client.py get /v1/items --format json
# Get items in YAML
./client.py get /v1/items --format yaml
# Pretty table
./client.py get /v1/items --format table
# POST with JSON body
./client.py post /v1/items --data '{"name":"example"}' --format yaml
The --format flag controls whether the output is printed as JSON, YAML, or a tabulated ASCII table using tabulate.