Designing a CLI Project
I’m considering delivering a full sample project that includes the structure, requirements.txt, main.py, and explanations on customization. I want to be concise but still provide enough detail for coding. I think I should start by asking a few clarifying questions, like which API or authentication method they’d prefer. I’m leaning towards a general CLI solution using Click for ease and requests for API calls, but I realize they may appreciate using argparse instead to keep things simple and to stick to standard libraries.Designing a Restful CLI Tool
I’m thinking about how to create an argparse-based code structure for main.py with subcommands like list, get, create, update, and delete for managing a resource. I’ll include an APIClient class for handling HTTP actions, using a base API like 'https://api.example.com', which the user can adjust. While they may prefer interactive CLI calls to any endpoint, I believe demonstrating resource-specific usage is better. I’ll lay out commands for getting, posting, updating, and deleting, addressing arguments like path, query parameters, JSON data, headers, and authentication. I'll also provide installation instructions for using setuptools as a console script.Structuring the CLI Tool
I’m thinking about providing an example file structure along with the code for a main Python script, such as cli.py or rest_cli/__main__.py. The focus will be on the code instead of heavy explanations.
For configuration, I’d like to include options to accept environment variables like RESTCLI_BASE_URL and RESTCLI_TOKEN. Possible features could be an optional --base-url argument, and a --token for authentication. I can also offer repeated --header options for custom headers and --params for key-value pairs, though that might get complex. For the body, I might allow --data as a raw string or a JSON file input, but I want to keep it straightforward.Defining CLI Syntax
I’m considering the CLI syntax and potential usage examples like:
restcli --base-url https://api.example.com --token $TOKEN get /users --param limit=10
restcli post /users --json '{"name": "Alice"}'
restcli delete /users/123
For building the Argparse, I'd set up the parser with options for --base-url, --token, and custom headers. Then I’d create subcommands for HTTP methods like get, post, and delete. When parsing parameters, I’ll convert them into a dictionary and define a perform_request(args) function for executing HTTP calls and handling responses, including error checking for JSON formatting.Planning the CLI Tool
I’m considering adding an optional --raw flag to show raw text and handling exceptions from requests. If an error occurs, I'll use sys.exit(1) and display reasoning when the status code is 400 or above. It might also be useful to include a --timeout option and a --verbose flag to echo request details and headers.
For the setup, I’ll draft a minimal pyproject.toml with project scripts. The structure of my answer will include a short introduction, project layout, the full cli.py code, and installation and usage instructions.
I’ll ensure to implement smart parsing for headers and parameters, requiring certain values, and I'll be mindful to print clear error messages when necessary. I’ll also follow Python best practices, like using if __name__ == "__main__": main(), and ensure to provide concise code, making things easy for the user. Now it’s time to get coding! Below is a self‑contained example of a Python CLI tool that can talk to (almost) any JSON-based REST API.
It:
- Uses
argparse (stdlib) and requests
- Supports HTTP methods: GET, POST, PUT, PATCH, DELETE
- Lets you pass base URL, headers, query params, JSON body, auth token
- Pretty‑prints JSON responses
You can adapt this as a template for your own API.
1. Dependencies
pip install requests
2. cli.py – the CLI tool
#!/usr/bin/env python3
"""
Generic REST API CLI.
Examples:
# Simple GET
python cli.py --base-url https://api.example.com get /users
# GET with query params
python cli.py --base-url https://api.example.com get /users \
--param limit=10 --param sort=created_at
# POST with JSON body
python cli.py --base-url https://api.example.com \
post /users --json '{"name": "Alice", "email": "alice@example.com"}'
# Use token from env var
export RESTCLI_TOKEN="your_token_here"
python cli.py --base-url https://api.example.com get /me
Environment variables:
RESTCLI_BASE_URL Default base URL if --base-url not given
RESTCLI_TOKEN Default Bearer token if --token not given
"""
import argparse
import json
import os
import sys
from typing import Dict, Any, List, Optional
import requests
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Command-line client for generic REST APIs."
)
# Global options
parser.add_argument(
"--base-url",
default=os.getenv("RESTCLI_BASE_URL"),
help="Base URL of the API (e.g., https://api.example.com). "
"Can also be set via RESTCLI_BASE_URL env var.",
)
parser.add_argument(
"--token",
default=os.getenv("RESTCLI_TOKEN"),
help="Bearer token for Authorization header. "
"Can also be set via RESTCLI_TOKEN env var.",
)
parser.add_argument(
"-H",
"--header",
action="append",
default=[],
help="Additional header, format: 'Key: Value'. "
"Can be given multiple times.",
)
parser.add_argument(
"--timeout",
type=float,
default=30.0,
help="Request timeout in seconds (default: 30).",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Print request details to stderr.",
)
subparsers = parser.add_subparsers(
dest="method",
required=True,
help="HTTP method to use",
)
# Common options for all HTTP methods
def add_common_request_args(sp: argparse.ArgumentParser):
sp.add_argument(
"path",
help="Request path, e.g. /users or users/123",
)
sp.add_argument(
"--param",
action="append",
default=[],
help="Query parameter in key=value form. "
"Can be given multiple times.",
)
sp.add_argument(
"--json",
help="JSON body string, e.g. '{\"name\": \"Alice\"}'. "
"Only used for methods that support a body.",
)
for method in ["get", "post", "put", "patch", "delete"]:
sp = subparsers.add_parser(method, help=f"HTTP {method.upper()}")
add_common_request_args(sp)
return parser
def parse_params(param_list: List[str]) -> Dict[str, str]:
params: Dict[str, str] = {}
for p in param_list:
if "=" not in p:
raise ValueError(f"Invalid param '{p}', expected key=value")
key, value = p.split("=", 1)
params[key] = value
return params
def parse_headers(
header_list: List[str],
token: Optional[str],
) -> Dict[str, str]:
headers: Dict[str, str] = {}
if token:
headers["Authorization"] = f"Bearer {token}"
for h in header_list:
if ":" not in h:
raise ValueError(f"Invalid header '{h}', expected 'Key: Value'")
key, value = h.split(":", 1)
headers[key.strip()] = value.strip()
# Default to JSON content-type when we send a JSON body
# Note: 'requests' will also set this when using json=, but this is explicit.
return headers
def parse_json_body(json_str: Optional[str]) -> Optional[Any]:
if not json_str:
return None
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON body: {e}") from e
def build_url(base_url: str, path: str) -> str:
return base_url.rstrip("/") + "/" + path.lstrip("/")
def print_response(resp: requests.Response) -> None:
# Status line
sys.stderr.write(f"HTTP {resp.status_code}\n")
content_type = resp.headers.get("Content-Type", "")
# Try pretty-print JSON if appropriate
if "application/json" in content_type.lower():
try:
data = resp.json()
print(json.dumps(data, indent=2, sort_keys=False))
return
except ValueError:
# Fall through to raw text
pass
# Non-JSON or unparsable
if resp.text:
print(resp.text)
def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if not args.base_url:
parser.error(
"Base URL is required. Use --base-url or set RESTCLI_BASE_URL."
)
method = args.method.lower()
url = build_url(args.base_url, args.path)
try:
params = parse_params(args.param)
headers = parse_headers(args.header, args.token)
body = parse_json_body(args.json)
except ValueError as e:
sys.stderr.write(str(e) + "\n")
return 1
if args.verbose:
sys.stderr.write(f"Request: {method.upper()} {url}\n")
if params:
sys.stderr.write(f" Params: {params}\n")
if headers:
sys.stderr.write(f" Headers: {headers}\n")
if body is not None:
sys.stderr.write(f" JSON body: {json.dumps(body)}\n")
try:
resp = requests.request(
method=method,
url=url,
headers=headers,
params=params,
json=body,
timeout=args.timeout,
)
except requests.RequestException as e:
sys.stderr.write(f"Request failed: {e}\n")
return 1
print_response(resp)
# Exit non-zero on HTTP error codes
if 400 <= resp.status_code:
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
3. Usage examples
# With base URL and no auth
python cli.py --base-url https://jsonplaceholder.typicode.com get /posts
# With query params
python cli.py --base-url https://jsonplaceholder.typicode.com \
get /comments --param postId=1
# POST with JSON body and verbose output
python cli.py --base-url https://api.example.com \
-v post /items --json '{"name": "Item 1", "price": 9.99}'
# Add custom headers
python cli.py --base-url https://api.example.com \
-H "X-Api-Key: mykey" \
get /status
4. Optional: install as a command
If you want a real restcli command instead of python cli.py:
Create pyproject.toml:
[project]
name = "restcli"
version = "0.1.0"
dependencies = ["requests"]
[project.scripts]
restcli = "cli:main"
Then install in editable mode:
pip install -e .
Now you can run:
restcli --base-url https://api.example.com get /users
If you have a specific REST API in mind (e.g., GitHub, a custom internal API), I can tailor this skeleton with resource-specific commands and validation.