Skip to content
Visual explainer 10h to learn 6 steps

Build a CLI app (e.g. expense tracker or weather logger)

A Git repo with modules, a dataclass model, JSON storage, an API call, tests and a README.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 34 of 34

In short

The build brings every module of the path together: a venv and Ruff-checked repo, dataclass models, JSON storage, an argparse CLI, one web API call and pytest tests, documented in a README.

Explained simply

Now you build the plan for real. This project uses almost everything from the path: a virtual environment, Git, dataclasses, files, a web API, argparse and pytest. Do not try to write it all at once. Build one small working piece, test it, commit it, then move to the next.

Start with the boring setup: a Git repository, a virtual environment and a linter called Ruff that catches mistakes and formats your code. Ten minutes of setup here keeps the whole project tidy.

Next, write the data model and the code that saves and loads it, with a test that saves some data and checks it comes back the same. Then add the command-line commands on top. The web API call comes after the core works, so a slow or broken API never blocks you.

Finish with more tests and a README that shows someone else how to install and use your tool. A project that a stranger can run in five minutes is a strong portfolio piece.

Press Play on a diagram to walk through it one step at a time.

LayersArchitecture of the CLI app
  1. 1
    cli.py

    argparse commands, printing, exit codes

  2. 2
    Service logic

    Add, list and summarise expenses

  3. 3
    models.py

    Expense dataclass and Category enum

  4. 4
    storage.py / rates.py

    JSON file storage and API client

  5. 5
    Files & network

    expenses.json and the remote API

FlowBuild order
  1. 1
    Repo, venv, Ruff

    git init, .gitignore, requirements

  2. 2
    Model & storage

    Save and load round-trip with tests

  3. 3
    CLI commands

    add, list, summary via argparse

  4. 4
    API integration

    With timeout and error handling

  5. 5
    Tests & README

    pytest green, usage examples written

CompareWhere each kind of test points
Unit tests
  • models and service functions
  • No files, no network
  • Many small, fast tests
  • Catch logic bugs
Storage tests
  • Real files in tmp_path
  • Round-trip, missing, broken file
  • A handful of tests
  • Catch data loss
CLI tests
  • Call main(argv) directly
  • API replaced by monkeypatch
  • Check output and exit code
  • Catch wiring mistakes

In depth

Repository, virtual environment and Ruff

Create the folder, run git init, and add a .gitignore with .venv/, __pycache__/, .pytest_cache/ and any local data files. Create the environment with python -m venv .venv and activate it (source .venv/bin/activate on Linux and macOS, .venv\Scripts\activate on Windows). Use a src layout, src/tracker/, and describe the project in pyproject.toml: name, version, requires-python, dependencies such as requests, an optional dev group with pytest and ruff, and the [project.scripts] entry for your command.

Install everything with pip install -e ".[dev]" so the package and your command work while you edit. Ruff is a fast linter and formatter: ruff check . finds bugs like unused imports and undefined names, ruff check --fix repairs the simple ones, and ruff format . formats the code. Configure it under [tool.ruff] in pyproject.toml and run both before each commit.

  • python -m venv .venv
  • pip install -e ".[dev]"
  • ruff check . && ruff format .
  • git commit -m "Set up project skeleton"

Storage that never corrupts your data

storage.py needs two functions: load_expenses(path) and save_expenses(items, path). Loading a file that does not exist yet should return an empty list, not crash, so the first run just works. Loading a file that is not valid JSON should raise a clear error that names the file, rather than silently starting empty and then overwriting the user's data.

Save atomically: write the JSON to a temporary file next to the real one, then call Path.replace to swap it in. A rename within one folder is atomic on the same file system, so a crash or power cut leaves either the old file or the new one, never half of each. Convert models with their to_dict and from_dict methods, and wrap the list in {"version": 1, "expenses": [...]} so the format can evolve. Test both functions with tmp_path, including the missing file and broken file cases.

Sequencetracker add, end to end
cli.py
service.py
storage.py
Disk
  1. 1add_expense(amount, category)
    cli.py to service.py: add_expense(amount, category)
  2. 2load_expenses(path)
    service.py to storage.py: load_expenses(path)
  3. 3read expenses.json
    storage.py to Disk: read expenses.json
  4. 4create and validate Expense
    service.py to service.py: create and validate Expense
  5. 5save_expenses(items, path)
    service.py to storage.py: save_expenses(items, path)
  6. 6write .tmp, then replace
    storage.py to Disk: write .tmp, then replace
  7. 7return the new Expense
    service.py to cli.py: return the new Expense

CLI commands that stay thin

Each subcommand handler in cli.py does three things: turn parsed arguments into proper types, call one service function, and print the result. All decisions, like how to group totals by month, live in service.py, where tests can call them directly.

Convert user input at the edge. argparse can parse the amount with type=Decimal and the date with type=date.fromisoformat, so the service only ever sees clean types. Catch expected errors, such as a ValueError from validation or a storage error, in one place in main, print a short message to stderr and return exit code 1. Unexpected errors should still show a traceback while you develop. For tables, f-strings with alignment are enough: f"{e.spent_on} {e.category.value:<8} {e.amount:>8}" lines up columns without any library.

Integrating the web API safely

Put every network detail in rates.py behind one function, such as get_rate(base, target) returning a Decimal. Inside it, use requests with a timeout, call raise_for_status(), and convert the JSON number with Decimal(str(value)). Read any API key from an environment variable and raise a clear error if it is missing.

Two design choices keep the rest of the program simple. First, convert requests exceptions into your own error, like RatesUnavailable, so cli.py can print "Could not reach the rates service, try again later" without knowing about requests. Second, cache results: rates change at most daily for most free APIs, so store the last answer with its date in a small JSON file and reuse it. The cache saves your rate limit and lets the tool work offline with yesterday's rate, with a warning.

Flowget_rate with a daily cache
  1. 1
    Check cache

    Rate for today already saved?

  2. 2
    Call the API

    timeout=10, raise_for_status()

  3. 3
    Parse to Decimal

    Decimal(str(value))

  4. 4
    Save to cache

    With today's date

  5. 5
    On failure

    Use the old rate with a warning, or raise RatesUnavailable

Tests that cover the core, and a README

Aim tests at the code with rules: model validation, the storage round-trip, missing and broken files, and service calculations such as totals per category. Test the CLI too, by calling main(["add", "12.50", "--file", str(path)]) and checking the exit code and capsys output. Never call the real API in tests: use monkeypatch.setattr to replace rates.get_rate with a function that returns a fixed Decimal, or one that raises RatesUnavailable to test the error path. The whole suite should run offline in about a second.

The README is the front door. Include one sentence on what the tool does, install steps (clone, create venv, pip install -e .), three or four usage examples copied from a real terminal, configuration (environment variables, data file location), how to run tests, and a license. Run every command in it once from a fresh clone to prove it works.

  • pytest -q runs the suite; pytest --cov=tracker shows untested lines
  • monkeypatch.setattr(rates, "get_rate", lambda b, t: Decimal("1.10"))
  • README: what, install, usage, config, tests, license

Learn it in 6 short steps

About 1h 40m each. Track them with a timer in your plan.

  1. 1
    Set up the repo, venv and Ruff~1h 40m
  2. 2
    Implement the dataclass model and storage~1h 40m
  3. 3
    Build the CLI commands with argparse~1h 40m
  4. 4
    Integrate a web API call~1h 40m
  5. 5
    Write pytest tests for core logic~1h 40m
  6. 6
    Write a README with usage examples~1h 40m

Key points

  • Keep logic out of cli.py so it can be tested without the command line.
  • Test storage with tmp_path so tests never touch real data.
  • Mock or wrap the API call so tests run offline.
  • Commit after each working step with a clear message.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
# test_storage.py
from datetime import date
from tracker.models import Expense, Category
from tracker.storage import save_expenses, load_expenses

def test_round_trip(tmp_path):
    path = tmp_path / "expenses.json"
    items = [Expense(12.5, Category.FOOD, date(2026, 3, 1))]
    save_expenses(items, path)
    assert load_expenses(path) == items

A round-trip test proves storage works without touching your real data.

Atomic JSON storage with clear errors

Step 1: a missing file means no expenses yet, so return an empty list. Step 2: broken JSON raises a StorageError naming the file, instead of silently losing data. Step 3: save writes to a .tmp file first. Step 4: Path.replace swaps the new file in with one atomic rename.

python
import json
from pathlib import Path
from tracker.models import Expense
class StorageError(Exception): pass
def load_expenses(path: Path) -> list[Expense]:
    if not path.exists(): return []
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        raise StorageError(f"{path} is not valid JSON: {e}") from e
    return [Expense.from_dict(d) for d in data["expenses"]]
def save_expenses(items: list[Expense], path: Path) -> None:
    tmp = path.with_suffix(".tmp")
    tmp.write_text(json.dumps({"version": 1, "expenses": [e.to_dict() for e in items]}, indent=2), encoding="utf-8")
    tmp.replace(path)

Testing the convert command without the network

The convert command calls rates.get_rate, which normally hits the web. Step 1: monkeypatch replaces it with a lambda returning a fixed rate. Step 2: tmp_path holds a data file with one expense. Step 3: call main with a list of arguments. Step 4: check the exit code and the printed total. The test runs offline and gives the same result every time.

python
from datetime import date
from decimal import Decimal
from tracker import cli, rates
from tracker.models import Category, Expense
from tracker.storage import save_expenses

def test_convert(tmp_path, monkeypatch, capsys):
    path = tmp_path / "data.json"
    save_expenses([Expense(Decimal("10.00"), Category.FOOD, date(2026, 3, 1))], path)
    monkeypatch.setattr(rates, "get_rate", lambda base, target: Decimal("1.10"))
    code = cli.main(["--file", str(path), "convert", "--to", "USD", "--month", "2026-03"])
    assert code == 0
    assert "11.00 USD" in capsys.readouterr().out

Quick reference

  • git init, .gitignore (.venv/, __pycache__/), python -m venv .venv
  • pip install -e ".[dev]" installs your package and dev tools together
  • ruff check --fix . then ruff format . before every commit
  • Missing data file: return []; broken data file: raise a clear error
  • Save atomically: write path.tmp, then tmp.replace(path)
  • Wrap requests errors in your own exception for cli.py to report
  • monkeypatch.setattr(module, "name", fake) keeps tests offline
  • Run every README command from a fresh clone before you share it

Common mistakes

  • Calling the real API in tests, making them slow and flaky.
  • Building every feature before writing a single test.
  • A README with no install or usage instructions.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why write to a temporary file and then call Path.replace when saving?

Question 2

2What should load_expenses do when the data file does not exist yet?

Question 3

3How should tests handle the function that calls the web API?

Question 4

4Where should the code that groups totals by month live?

Question 5

5What does pip install -e ".[dev]" do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a test that saving an empty list and loading it back returns an empty list.

  2. Exercise 2medium

    Write totals_by_category(expenses) in service.py returning a dict from category value to Decimal total, and a test for it.

  3. Exercise 3hard

    Write get_rate(base, target) that calls an API with a timeout and turns any requests error into RatesUnavailable.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do I make my Python project installable as a command?
Add a [project.scripts] entry in pyproject.toml, such as tracker = "tracker.cli:main", then run pip install -e . in your virtual environment. pip creates a tracker command that calls main().
What is Ruff and do I need it?
Ruff is a very fast Python linter and formatter written in Rust. It replaces several older tools like flake8 and isort, and catching unused imports and undefined names early is worth the two minutes of setup.
How many tests should a capstone project have?
There is no magic number. Cover every rule in the service layer, the storage round-trip and error cases, and one test per CLI command; for a small tool that is often 15 to 30 short tests.
What should a good README include?
What the tool does, how to install it, real usage examples, configuration such as environment variables, how to run the tests, and the license.
ShareXLinkedInWhatsApp