The user wants a Python CLI tool to interact with a REST API.
This is a broad request, so I need to make some design decisions to provide a useful, generic, and extensible example.
Key Components:
-
Argument Parsing: Need a way to handle command-line arguments (URL, method, headers, data, etc.). argparse is the standard library choice, but click or typer are more modern and powerful. I will use argparse to avoid external dependencies for the core logic, or better yet, I'll provide a version using requests and argparse because they are the most common "standard" way to do this without too much boilerplate. Actually, httpie or curl exist, so re-inventing a generic client isn't usually the goal. The goal is likely a tool to interact with a specific API (like a todo list or user management) or a generic wrapper.
- Self-correction: A generic wrapper (like
requests-cli) is complex. A specific client for a sample API (like JSONPlaceholder) is more educational. I will create a tool that interacts with JSONPlaceholder as a concrete example, but structure it so it can be adapted to any API.
-
HTTP Requests: The requests library is the de facto standard in Python. I must use it.
-
Configuration/Environment: Hardcoding API keys is bad practice. I should include support for environment variables (e.g., API_KEY).
-
Output Formatting: Raw JSON is hard to read. Using json.dumps with indentation is good. Adding color (via rich or colorama) makes it better, but sticking to standard libraries (json, sys) ensures it runs everywhere without a massive requirements.txt if the user just wants the logic.
- Decision: I will use
requests (external) and argparse (internal). I will output formatted JSON.
Structure of the Solution:
- Setup: Explain prerequisites (installing
requests).
- Code Implementation:
- Import necessary modules.
- Setup
argparse with subparsers (e.g., get-users, get-user, create-user). This is more "CLI tool" like than just passing raw HTTP flags.
- Define a service class/function to handle the API calls.
- Handle errors (network issues, 4xx/5xx responses).
- Format output.
- Usage Examples: Show how to run the commands.
Drafting the Code (Mental or scratchpad):
Refining the Request:
The user asked for "Develop a Python CLI tool". This implies a script that does something useful.
I will provide a robust template using argparse and requests.
Step-by-Step Implementation Plan:
- Imports:
argparse, requests, json, sys, os.
- Constants: Base URL.
- Helper Functions:
print_json(data): Pretty print.
handle_response(response): Check status codes, raise errors or return json.
- Command Functions:
cmd_list(args): GET /posts
cmd_get(args): GET /posts/{id}
cmd_create(args): POST /posts
- Main block: Setup
argparse subparsers and link them to functions.
Alternative approach: A generic HTTP client wrapper.
While useful, specific "business logic" wrappers (like a "Todo CLI" or "User CLI") are usually what people want when building a tool. I will stick to the "Specific API Client" approach (using JSONPlaceholder) because it demonstrates how to handle data structures, not just raw HTTP streams.
Adding Security/Best Practices:
- Mention
python-dotenv for API keys.
- Mention User-Agent headers.
Final Polish:
I will write the code in a single file for copy-paste ease, but explain how to structure it for a package.
Let's write the code.
- Use
argparse for subcommands (list, get, create).
- Use
requests for HTTP.
- Use
json for output.
(Self-Correction during coding): What if the user wants a generic curl-like tool?
I should probably mention that httpie exists, but code a specific client as it's more likely a "development" task. I will stick to the JSONPlaceholder example as it's the standard "Hello World" for REST.
Let's add a "configuration" part, showing how to set an API Key via environment variable, even if the test API doesn't strictly need it, just to show how it's done.
Output Plan:
- Prerequisites:
pip install requests
- The Script:
api_tool.py
- Explanation: How it works (argparse, requests, error handling).
- Usage: Command examples.
Let's refine the code snippet.
I will create a class APIClient to encapsulate the session and base URL. This is cleaner.
class APIClient:
def __init__(self, base_url):
self.base_url = base_url
# ...
def get_post(self, id): ...
And the CLI logic separates the "Interface" from the "Logic".
Okay, ready to generate the response.
To build a robust CLI tool in Python, the best approach is to use the requests library for handling HTTP calls and the built-in argparse library to handle command-line arguments.
Below is a complete, runnable example. We will use JSONPlaceholder (a free fake API) so you can run the code immediately without setting up a server.
Prerequisites
You will need to install the requests library:
pip install requests
The Python CLI Tool
Save the following code into a file named rest_cli.py.
This tool implements a generic pattern: it separates the API Logic (how we talk to the server) from the CLI Logic (how we parse user input).
import argparse
import requests
import json
import sys
# --- 1. Configuration & Constants ---
BASE_URL = "https://jsonplaceholder.typicode.com/posts"
# --- 2. API Client Logic ---
class APIClient:
"""Handles the actual HTTP communication."""
def __init__(self, base_url):
self.base_url = base_url
def list_items(self):
try:
response = requests.get(self.base_url)
response.raise_for_status() # Check for HTTP errors
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error connecting to API: {e}")
sys.exit(1)
def get_item(self, item_id):
try:
response = requests.get(f"{self.base_url}/{item_id}")
if response.status_code == 404:
print(f"Error: Item {item_id} not found.")
return None
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
sys.exit(1)
def create_item(self, title, body, user_id):
payload = {
"title": title,
"body": body,
"userId": user_id
}
headers = {'Content-type': 'application/json; charset=UTF-8'}
try:
response = requests.post(self.base_url, json=payload, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error creating item: {e}")
sys.exit(1)
def delete_item(self, item_id):
try:
response = requests.delete(f"{self.base_url}/{item_id}")
response.raise_for_status()
return response.status_code == 200
except requests.exceptions.RequestException as e:
print(f"Error deleting item: {e}")
sys.exit(1)
# --- 3. Output Formatting ---
def print_json(data):
"""Pretty print JSON data."""
print(json.dumps(data, indent=4))
# --- 4. CLI Interface Logic ---
def main():
parser = argparse.ArgumentParser(description="A simple CLI REST API Client")
subparsers = parser.add_subparsers(dest="command", help="Action to perform")
# Subcommand: list
parser_list = subparsers.add_parser("list", help="List all posts")
# Subcommand: get
parser_get = subparsers.add_parser("get", help="Get a specific post")
parser_get.add_argument("id", type=int, help="The ID of the post")
# Subcommand: create
parser_create = subparsers.add_parser("create", help="Create a new post")
parser_create.add_argument("--title", required=True, help="Post title")
parser_create.add_argument("--body", required=True, help="Post body content")
parser_create.add_argument("--user-id", type=int, required=True, help="User ID")
# Subcommand: delete
parser_delete = subparsers.add_parser("delete", help="Delete a post")
parser_delete.add_argument("id", type=int, help="The ID of the post to delete")
args = parser.parse_args()
client = APIClient(BASE_URL)
# Route commands to API calls
if args.command == "list":
data = client.list_items()
print_json(data)
elif args.command == "get":
data = client.get_item(args.id)
if data:
print_json(data)
elif args.command == "create":
print("Creating post...")
data = client.create_item(args.title, args.body, args.user_id)
print_json(data)
print("\nSuccess! (Note: Fake API returns 201, but data isn't actually saved server-side)")
elif args.command == "delete":
if client.delete_item(args.id):
print(f"Successfully deleted post {args.id}")
else:
parser.print_help()
if __name__ == "__main__":
main()
How to use it
Open your terminal and run the following commands to test the different features.
1. View Help:
python rest_cli.py --help
python rest_cli.py create --help
2. List all posts:
python rest_cli.py list
3. Get a specific post (ID 1):
python rest_cli.py get 1
4. Create a new post:
python rest_cli.py create --title "My First CLI Post" --body "This is content." --user-id 1
5. Delete a post (ID 1):
python rest_cli.py delete 1
Implementation Details
argparse Subparsers: This is the standard way to build tools like git or docker. Instead of messy flags like --action=get, you get clean verbs: rest_cli.py get 1.
requests Library: We use response.raise_for_status(). This is crucial; otherwise, your script might continue running even if the server returned a 404 or 500 error.
try...except blocks: Network calls fail often (no wifi, server down). The try blocks catch these errors and print a readable message instead of crashing with a raw Python stack trace.
- Modularity: The
APIClient class is separated from the argument parsing. This means you can take that class and reuse it in a different script (like a GUI app or a Cron job) without rewriting the HTTP logic.