Read a saved CoinGecko price for an explicit asset and currency
Python
Read a saved CoinGecko `/simple/price` JSON response, select one asset ID and quote currency from CLI arguments, and print its finite numeric price while making clear it is not a current quote.
CoinGecko documents `/simple/price` responses as objects keyed by coin ID, with target-currency fields such as `usd` containing a numeric price. This offline Python 3.12 example reads a saved response, selects exactly one ID and currency, and rejects missing, null, non-numeric, or non-finite values. It does not contact CoinGecko or establish price freshness.
Before you start
Intended runner: Python 3.12; no third-party packages or installation are required.
Provide a saved JSON object matching the documented simple-price response shape, either as a local file or on stdin.
Supply one explicit asset ID and one quote-currency key as positional CLI arguments.
No credentials, live API access, or external service calls are used.
Build and check
Save the code as `saved_price.py`.
Save a simple-price JSON response locally, or prepare the same JSON text for stdin.
Run the script with the input path, explicit asset ID, and quote currency; use `-` as the path for stdin.
Confirm the printed value is labeled as a saved observation, not a current quote.
Try invalid or missing input cases and check that errors go to stderr with a nonzero exit status.
Limits to understand
Only reads the selected field from saved JSON; it does not fetch data, verify timestamps, or assess freshness.
The source docs establish the response shape and numeric price field, but do not specify a minimum supported Python version; Python 3.12 is the intended runner.
Input is read entirely into memory; use only appropriately sized local fixtures.
What this example adds
The task is narrowed to reading one explicitly selected ID/currency pair from a saved response rather than constructing or sending a live API request. The CLI accepts a file or stdin; validation distinguishes malformed JSON, absent selections, null/non-numeric values, and non-finite numbers, and output labels the value as a saved observation.
Run it
Save the code as `saved_price.py`, then run `python3.12 saved_price.py response.json bitcoin usd`. Use `-` instead of the file path to read JSON from stdin, for example `cat response.json | python3.12 saved_price.py - bitcoin usd`.
Saved observation: bitcoin/usd = 76975
This is a saved observation, not a current quote.
INSPECT THE SCRIPT
Inspect, copy and run the documented checks.
This browser preview builds code locally. It does not contact an API or run the code.
Default example ready.
Python example
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 OpenViST contributors
import argparse
import json
import math
import pathlib
import sys
def main():
parser = argparse.ArgumentParser(
description="Read one price from a saved CoinGecko simple-price JSON response."
)
parser.add_argument("file", help="path to a saved JSON response, or - for stdin")
parser.add_argument("asset_id", help="explicit CoinGecko asset ID, such as bitcoin")
parser.add_argument("currency", help="quote currency key, such as usd")
args = parser.parse_args()
if not args.asset_id or not args.currency:
parser.error("asset_id and currency must not be empty")
try:
if args.file == "-":
text = sys.stdin.read()
else:
text = pathlib.Path(args.file).read_text(encoding="utf-8")
except OSError as exc:
print(f"error: cannot read input: {exc}", file=sys.stderr)
return 2
try:
response = json.loads(text, parse_constant=lambda value: (_ for _ in ()).throw(
ValueError(f"invalid non-finite JSON constant: {value}")
))
except (json.JSONDecodeError, ValueError) as exc:
print(f"error: invalid JSON: {exc}", file=sys.stderr)
return 2
if not isinstance(response, dict):
print("error: expected a top-level JSON object", file=sys.stderr)
return 2
asset = response.get(args.asset_id)
if not isinstance(asset, dict):
print(f"error: asset ID {args.asset_id!r} is absent or is not an object", file=sys.stderr)
return 2
if args.currency not in asset:
print(f"error: currency {args.currency!r} is absent for {args.asset_id!r}", file=sys.stderr)
return 2
price = asset[args.currency]
if isinstance(price, bool) or not isinstance(price, (int, float)):
print("error: price must be a non-null JSON number", file=sys.stderr)
return 2
if not math.isfinite(price):
print("error: price must be finite", file=sys.stderr)
return 2
print(f"Saved observation: {args.asset_id}/{args.currency} = {price}")
print("This is a saved observation, not a current quote.")
return 0
if __name__ == "__main__":
sys.exit(main())
What to verify after running
Normal case: provide `{"bitcoin":{"usd":76975}}` and run with `bitcoin usd`; verify the two expected output lines.
Selection checks: try an unknown asset ID, an asset value that is not an object, and a missing currency key; each should produce a clear stderr error and nonzero exit.
Value checks: try null, a string, a boolean, and a JSON non-finite constant such as `NaN`; each must be rejected.
Malformed/empty checks: try an empty file and malformed JSON; both should fail without printing a price.
Missing-file check: pass a nonexistent path and verify the read error is reported to stderr with nonzero exit.
Stdin check: pipe a valid synthetic JSON object into the command with `-` and verify it selects the requested pair.
Request or format preview
Illustrative preview. No provider response, price or balance is fetched.
Code license: MIT. Keep the license notice with your copy.
Example version 0.1.0 · Documentation reviewed 2026-10-11.
Executed 6 synthetic local fixture cases in isolated CPython 3.12.15 on GitHub Actions, without network access. Declared exit codes, output assertions and input integrity checks passed. Live services, installed third-party packages and production behavior remain outside scope. Editorial approval is still required.