typestar

fetch_json.py in Python

Fetch a JSON API and pretty-print it, no dependencies.

import json
import sys
import urllib.request


def fetch(url, timeout=10):
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.load(resp)


def main():
    if len(sys.argv) != 2:
        print("usage: fetch_json.py URL")
        raise SystemExit(1)
    data = fetch(sys.argv[1])
    print(json.dumps(data, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()

How it works

  1. urllib.request sends the request with an Accept header.
  2. The response streams straight into json.load.
  3. json.dumps(indent=2) pretty-prints, keys sorted.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
433
Tokens
127
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 1 of 5 in Encore, step 68 of 72 in Language basics.

← Previous Next →