Charts, HTTP and other working libraries

A principal will not read a list of 1,200 floats. matplotlib (and seaborn) turn columns into a picture. requests (or httpx) pull JSON from a weather service, a payment sandbox, a school API. datetime, logging and json from the standard library sit beside them. This chapter is the connective tissue of real applications: show a human a chart, talk to another computer, leave a log.

Charts from numbers

A picture that a principal can read in five seconds.

You will be able to

  • Know why you plot (a human contract)
  • Treat an HTTP JSON body as a dict you already understand
  • Place logging and datetime in a real app

A chart is a sentence

Title, axis labels with units, a legend if two series. Without those, a red line is decoration. matplotlib’s pyplot is the usual starting API: plot, bar, hist, savefig. savefig("house_avg.png", dpi=150) is what you attach to an email; show() is for you on a laptop.

Plot the derived table from the pipeline, not the raw CSV. If the pipeline is wrong, the chart will lie confidently. seaborn sits on matplotlib and makes statistical plots less ugly with less code — still the same DataFrame.

HTTP is just another extract

requests.get(url, timeout=10) returns a response. response.raise_for_status() turns 404 into an error you can catch. response.json() is a dict or list — Intermediate JSON-shaped records. Always set a timeout; a hung GET freezes a kiosk.

APIs fail. Cache yesterday’s weather in SQLite if today’s request dies. Never put API keys in source code — environment variables, the same config lesson as chapter one. For local demos, fake the JSON as a dict (as this sandbox does).

logging, datetime, json — already installed

print is not a log. logging.info("loaded %s rows", n) can go to a file with timestamps. datetime.now() for run dates; datetime.date for “today’s attendance” without a timezone surprise. json.dumps for writing a settings file; json.loads for reading one.

Other libraries you will meet on the job: openpyxl (Excel), pillow (images), fastapi or flask (web), sqlalchemy (databases beyond sqlite3), pytest (the real test runner). You do not need them all today. You need to know they exist so you do not reinvent Excel with print.

Words that matter

HTTP GET
Ask a server for a resource; the body is often JSON.
Status code
200 ok, 404 missing, 500 the other computer broke.
savefig
Write a matplotlib figure to a PNG/PDF file.
Timeout
Give up waiting for the network so the app can recover.

Common mistakes

Avoid: requests.get(url) with no timeout in a school kiosk.

Do this: timeout=10 (or similar) and a fallback cache.

Avoid: A chart with no units on the axis.

Do this: Label °C, counts, rupees — a principal is not a mind-reader.

On a full Python install — matplotlib + requests

The usual pair: pull or compute a series, draw it, save a PNG. Swap requests for reading a CSV — the plot code stays.

pip install matplotlib requests

Bar chart from a dict, plus a sketched GET of JSON weather.

Real library code (not run in this browser sandbox)

import matplotlib.pyplot as plt
import requests

house_avg = {"Green": 72, "Blue": 68, "Red": 81}
plt.figure()
plt.bar(house_avg.keys(), house_avg.values())
plt.ylabel("Mean marks")
plt.title("House averages — term 1")
plt.savefig("house_avg.png", dpi=150)

r = requests.get("https://example.com/weather", timeout=10)
r.raise_for_status()
payload = r.json()
print(payload["temp_c"])

Example program — A JSON payload already in a dict

This is response.json(). Pull temp_c and decide a warning.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Read an API-shaped dict

payload has ok set to True and n set to 12. Print a line containing 12.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. response.json() in requests typically gives you…
2. matplotlib.savefig is useful because…

Progress is stored in a browser cookie on this device.