I'm zeroing in on the core of the problem: a Python CLI interacting with a REST API. The immediate needs are clear. I'm focusing on the language (Python) and the interface (command-line). The user's request is straightforward, and the initial building blocks are coming into view.
Mapping Out Implementation Steps
\n\n
My current thinking is focused on tool selection. I'm leaning heavily towards typer and rich for the CLI. It's the most modern route. Considering the user's needs, I've outlined the core functionalities: argument parsing, HTTP request handling using requests, and pretty output with rich. I'm starting to visualize the structure of the Python script. It'll have subcommands, a clean interface, and error handling.
Outlining Code Structure
\n\n
I'm now deep into the actual code outline. I've blocked out the imports, including typer, requests, and rich. The BASE_URL is set. I'm building out the CLI structure with typer.Typer(). I'm focusing on the subcommands: list, get <id>, create, and delete <id>, as well as error handling for API call failures. I'm creating example responses for testing before I begin wiring the commands to requests calls.
Planning the Command Functions
\n\n
My current focus is on the implementation of the core commands. I'm fleshing out the functions for list, get, create, and delete. Each will need to handle API calls using requests and display the results using rich. The error handling is becoming clearer. I'm making sure to address edge cases. I'm testing the calls to JSONPlaceholder to finalize the argument types.
Structuring the Implementation Guide
\n\n
My current thinking is focused on organizing the guide. I'm solidifying the prerequisites (pip installs) and the file structure. I'm ensuring there are clear explanations and practical usage examples. I'm focusing on enhancements like authentication as a possible extension. I'll make the code easily copy-pasteable. I'm aiming for clarity in explaining each section to help the user understand the underlying principles.
This guide will walk you through creating a robust, modern Python CLI tool to interact with a REST API.
For this project, we will use:
Typer: A modern library for building CLI applications (easier and cleaner than argparse).
Requests: The standard library for making HTTP requests.
Rich: A library for beautiful terminal formatting (colors, tables, JSON).
JSONPlaceholder: A free fake API for testing (we will interact with the /posts endpoint).
1. Setup and Installation
First, create a project folder and install the necessary libraries:
bash
mkdir my-api-cli
cd my-api-cli
pip install typer requests rich
2. The Python Code (main.py)
Create a file named main.py and paste the following code. This creates a CLI with commands to List, Get, Create, and Delete posts.
python
3. How to Use It
Typer automatically generates help documentation and handles command-line arguments for you.
View Help
See all available commands:
bash
python main.py --help
List items (GET)
By default fetches 10 items:
bash
python main.py list
Fetch 5 items:
bash
python main.py list --limit 5
Get a single item (GET)
Fetch post #1:
bash
python main.py get 1
Create an item (POST)
Note the quotes around the text strings:
bash
python main.py create "My CLI Post" "This was created with Python"
(Note: JSONPlaceholder returns a fake success ID (usually 101), but doesn't actually update the database).
Delete an item (DELETE)
This includes a user confirmation prompt (y/N):
bash
python main.py delete 1
4. How it Works
app = typer.Typer(): Initializes the application.
@app.command(): This decorator tells Python that the function immediately following it is a CLI command.
Type Hints (e.g., post_id: int): Typer reads these hints. If a user tries to pass "hello" into an ID field, the CLI will automatically throw a readable error saying value is not a valid integer.
requests: Handles the HTTP verb (GET, POST, DELETE) and headers.
console.print / rprint: These replace standard print() statements to provide colored text, formatted JSON, and tables.
5. Enhancements for Production
If you were building this for a real production API (like AWS, GitHub, or Stripe), you would add:
Authentication: Add a --api-key option to the main callback or read it from an environment variable (os.getenv("API_KEY")).
Config Files: Use a library like python-dotenv to load .env files so users don't have to type credentials every time.
Packaging: Use setuptools or poetry to package this so users can install it via pip install mytool and run it as mytool command instead of python main.py command.
import typer
import requests
import sys
from rich.console import Console
from rich.table import Table
from rich import print as rprint
# Initialize Typer app and Rich console
app = typer.Typer()
console = Console()
# Configuration
BASE_URL = "https://jsonplaceholder.typicode.com/posts"
def handle_error(response):
"""Helper to handle non-200 responses."""
if response.status_code not in (200, 201):
rprint(f"[bold red]Error:[/bold red] API returned status code {response.status_code}")
sys.exit(1)
@app.command()
def list(limit: int = typer.Option(10, help="Number of posts to display")):
"""
Fetch and list all posts (defaults to top 10).
"""
console.print(f"[bold blue]Fetching top {limit} posts...[/bold blue]")
try:
response = requests.get(BASE_URL)
handle_error(response)
data = response.json()[:limit]
# Create a pretty table
table = Table(title="Posts Listing")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("User ID", style="green")
for post in data:
table.add_row(str(post["id"]), post["title"], str(post["userId"]))
console.print(table)
except requests.exceptions.RequestException as e:
rprint(f"[bold red]Connection Error:[/bold red] {e}")
@app.command()
def get(post_id: int):
"""
Get details of a specific post by ID.
"""
url = f"{BASE_URL}/{post_id}"
try:
response = requests.get(url)
if response.status_code == 404:
rprint(f"[bold red]Post with ID {post_id} not found.[/bold red]")
return
handle_error(response)
data = response.json()
# Print pretty JSON
rprint(f"[bold green]Found Post #{post_id}:[/bold green]")
console.print_json(data=data)
except requests.exceptions.RequestException as e:
rprint(f"[bold red]Connection Error:[/bold red] {e}")
@app.command()
def create(title: str, body: str, user_id: int = 1):
"""
Create a new post.
"""
payload = {
"title": title,
"body": body,
"userId": user_id
}
rprint("[bold yellow]Sending data to API...[/bold yellow]")
try:
# POST request
response = requests.post(BASE_URL, json=payload)
handle_error(response)
data = response.json()
rprint(f"[bold green]Success![/bold green] Created post with ID: {data.get('id')}")
rprint(data)
except requests.exceptions.RequestException as e:
rprint(f"[bold red]Connection Error:[/bold red] {e}")
@app.command()
def delete(post_id: int):
"""
Delete a post by ID.
"""
url = f"{BASE_URL}/{post_id}"
if not typer.confirm(f"Are you sure you want to delete Post {post_id}?"):
rprint("[bold red]Aborted.[/bold red]")
raise typer.Abort()
try:
response = requests.delete(url)
handle_error(response)
rprint(f"[bold green]Post {post_id} successfully deleted.[/bold green]")
except requests.exceptions.RequestException as e:
rprint(f"[bold red]Connection Error:[/bold red] {e}")
if __name__ == "__main__":
app()