Python Intermediate Lesson 8: JSON and APIs

Python Intermediate Lesson 8: JSON and APIs 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 8 of 10

Advertisement
In this article
  1. JSON in Python
  2. Calling an API
  3. Good habits
  4. Practice

Almost every web service (exchange rates, GST lookups, courier tracking, your own company’s systems) speaks JSON over HTTP.

JSON in Python

import json
data = json.loads(text)            # JSON text -> dict/list
text = json.dumps(data, indent=2)  # dict/list -> JSON text
json.load(open("rates.json"))      # from a file

Calling an API

import requests
r = requests.get("https://api.example.com/rates", params={"base": "INR"}, timeout=10)
r.raise_for_status()               # stop on 4xx/5xx instead of parsing an error page
data = r.json()

The lesson script reads the same structure from rates.json so it runs offline; swap in the two lines above when you have a real API.

Good habits

  • Always set a timeout, or a dead server hangs your script forever.
  • Keep API keys out of the script: os.environ["RATES_API_KEY"], set once on the PC.
  • Respect rate limits; cache responses you reuse (save the JSON with today’s date in the file name).
  • Check the fields you need exist: data.get("rates", {}).get("USD").
πŸ’‘ 1 / rate flips the direction: if 1 INR = 0.01192 USD, then 1 USD = β‚Ή83.89.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 8 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 967 B
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 390 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *