Part 12 / Stage 2
Web, APIs and databases
Goal: Fetch data from web APIs, read their JSON answers safely, and store and query that data in an SQLite database. Time: ~1 hour
What you will learn
- How the web works: client and server, URL parts, HTTP methods, status codes, headers, JSON bodies
- What an API and a REST API are, how to read API docs, query parameters, API keys
- Making requests with the standard library:
urllib.request+json, timeouts, errors - The same calls with the popular
requestslibrary (side by side) - Reading nested JSON with
.get()defaults and turning it into dataclasses - Being a good API citizen: rate limits, retries with backoff, caching
- Why use a database, and what tables, rows, columns and primary keys are
- SQL basics:
CREATE,INSERT,SELECT,WHERE,ORDER BY,UPDATE,DELETE,GROUP BY,JOIN sqlite3in Python, with parameterised queries (?) to stop SQL injection- A tiny data-access layer (the repository idea)
Everything runs offline. The examples use committed
sample_*.jsonfiles, and a tiny fake API,examples/local_api.py, that runs on your own computer. Your code makes real HTTP calls to it, but no internet is needed. Run the snippets that sayimport local_apifrom inside theexamples/folder.
Topics in this part
Practice
Python workbench — write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Use only the standard library. Every exercise runs offline: no internet, no pip install.
Exercise 1: URL inspector
Scenario: A train-booking app logs every API URL it calls, and you want to read them easily. What to do:
- Write
url_parts(url)that returns a dict with the keysscheme,host,pathandparams(the query string as a plain dict: one value per key). - Write
build_url(base, params)that returnsbase?plus the encoded params. - Print each key and value of
url_parts(TRAIN_URL)askey: value, then printbuild_url("https://api.example.com/v1/search", {"q": "Rajdhani Express", "class": "3A"}).
Starting data:
TRAIN_URL = "https://api.example.com/v1/trains?from=NDLS&to=BCT&date=2026-08-15"
Sample output:
scheme: https
host: api.example.com
path: /v1/trains
params: {'from': 'NDLS', 'to': 'BCT', 'date': '2026-08-15'}
https://api.example.com/v1/search?q=Rajdhani+Express&class=3A
💡 Hint: urlparse(url) gives .scheme, .hostname, .path, .query. dict(parse_qsl(query)) makes the plain dict. urlencode(params) turns the space into +.
Show the solution to Exercise 1
"""Exercise 1: URL inspector (urlparse, parse_qsl, urlencode).
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
from urllib.parse import parse_qsl, urlencode, urlparse
TRAIN_URL = "https://api.example.com/v1/trains?from=NDLS&to=BCT&date=2026-08-15"
def url_parts(url: str) -> dict:
parts = urlparse(url)
return {
"scheme": parts.scheme,
"host": parts.hostname,
"path": parts.path,
"params": dict(parse_qsl(parts.query)),
}
def build_url(base: str, params: dict) -> str:
return f"{base}?{urlencode(params)}"
def main() -> None:
for name, value in url_parts(TRAIN_URL).items():
print(f"{name}: {value}")
print(build_url(
"https://api.example.com/v1/search", {"q": "Rajdhani Express", "class": "3A"}
))
if __name__ == "__main__":
main()
Exercise 2: Status code helper
Scenario: Your app must show a clear message for every HTTP status code, and decide if it is worth trying again. What to do:
- Write
status_message(code)that returns e.g.404 Not Found: client error, fix the request. UseHTTPStatus(code).phrasefor the name and theFAMILIESdict for the meaning. - Write
should_retry(code)that returnsTrueonly for429and any 5xx code. - Print a line for each of
200, 201, 301, 400, 404, 429, 500, 503, adding(retry)or(no retry).
Starting data:
FAMILIES = {
2: "success",
3: "redirect",
4: "client error, fix the request",
5: "server error, try again later",
}
Sample output:
200 OK: success (no retry)
201 Created: success (no retry)
301 Moved Permanently: redirect (no retry)
400 Bad Request: client error, fix the request (no retry)
404 Not Found: client error, fix the request (no retry)
429 Too Many Requests: client error, fix the request (retry)
500 Internal Server Error: server error, try again later (retry)
503 Service Unavailable: server error, try again later (retry)
💡 Hint: code // 100 gives the first digit (404 // 100 is 4). from http import HTTPStatus.
Show the solution to Exercise 2
"""Exercise 2: Status code helper (HTTPStatus, status families, retry rule).
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
from http import HTTPStatus
FAMILIES = {
2: "success",
3: "redirect",
4: "client error, fix the request",
5: "server error, try again later",
}
def status_message(code: int) -> str:
return f"{code} {HTTPStatus(code).phrase}: {FAMILIES[code // 100]}"
def should_retry(code: int) -> bool:
return code == 429 or code >= 500
def main() -> None:
for code in (200, 201, 301, 400, 404, 429, 500, 503):
retry = "retry" if should_retry(code) else "no retry"
print(f"{status_message(code)} ({retry})")
if __name__ == "__main__":
main()
Exercise 3: Safe profile reader
Scenario: A user-profile API leaves out fields it does not have, and sends null for others.
What to do: Write summarise_profile(data) that returns a list of 5 lines: name, city with latitude and longitude, phone, company name and skills. Use these defaults: city unknown, latitude/longitude ?, phone not given, company freelancer, skills none. Print the lines for json.loads(RESPONSE_TEXT), an empty line, then the lines for {"name": "New User"}.
Starting data:
RESPONSE_TEXT = """
{
"id": 7,
"name": "Kiran Rao",
"address": {"city": "Hyderabad", "geo": {"lat": "17.38", "lng": "78.48"}},
"company": null,
"skills": ["Python", "SQL"]
}
"""
Sample output:
Name: Kiran Rao
City: Hyderabad (17.38, 78.48)
Phone: not given
Company: freelancer
Skills: Python, SQL
Name: New User
City: unknown (?, ?)
Phone: not given
Company: freelancer
Skills: none
💡 Hint: data.get("address", {}) gives an empty dict when the key is missing. company exists but is None, so use data.get("company") or {}. ", ".join([]) is "", and "" or "none" is "none".
Show the solution to Exercise 3
"""Exercise 3: Read a nested JSON profile safely with .get() defaults.
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
import json
RESPONSE_TEXT = """
{
"id": 7,
"name": "Kiran Rao",
"address": {"city": "Hyderabad", "geo": {"lat": "17.38", "lng": "78.48"}},
"company": null,
"skills": ["Python", "SQL"]
}
"""
def summarise_profile(data: dict) -> list[str]:
address = data.get("address", {})
geo = address.get("geo", {})
company = data.get("company") or {} # null -> None -> {}
return [
f"Name: {data['name']}",
f"City: {address.get('city', 'unknown')} "
f"({geo.get('lat', '?')}, {geo.get('lng', '?')})",
f"Phone: {data.get('phone', 'not given')}",
f"Company: {company.get('name', 'freelancer')}",
f"Skills: {', '.join(data.get('skills', [])) or 'none'}",
]
def main() -> None:
data = json.loads(RESPONSE_TEXT)
for line in summarise_profile(data):
print(line)
print()
for line in summarise_profile({"name": "New User"}): # almost empty answer
print(line)
if __name__ == "__main__":
main()
Exercise 4: Products into dataclasses
Scenario: A handicrafts shop's API returns its products as JSON. You want real objects, not dicts. What to do:
- Make a dataclass
Productwithproduct_id,name,priceandstock(default0), plus a propertyin_stockthat isTruewhenstock > 0. - Write
parse_products(data)that returns a list ofProduct. Some items have no"stock"key. - Print the third product, then the products that are in stock and cost under ₹1,000, cheapest first, then the total stock value (
price * stockadded up).
Starting data:
RESPONSE_TEXT = """
{
"count": 5,
"products": [
{"id": 11, "name": "Clay water pot", "price": 380, "stock": 14},
{"id": 12, "name": "Brass diya set", "price": 1250, "stock": 3},
{"id": 13, "name": "Jute bag", "price": 199},
{"id": 14, "name": "Cotton saree", "price": 2400, "stock": 0},
{"id": 15, "name": "Steel tiffin", "price": 650, "stock": 9}
]
}
"""
Sample output:
Product(product_id=13, name='Jute bag', price=199, stock=0)
In stock under ₹1,000:
Clay water pot ₹380
Steel tiffin ₹650
Stock value: ₹14,920
💡 Hint: item.get("stock", 0). Sort with sorted(..., key=lambda p: p.price). Print the name with {product.name:<16}.
Show the solution to Exercise 4
"""Exercise 4: Turn a products API response into dataclasses.
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
import json
from dataclasses import dataclass
RESPONSE_TEXT = """
{
"count": 5,
"products": [
{"id": 11, "name": "Clay water pot", "price": 380, "stock": 14},
{"id": 12, "name": "Brass diya set", "price": 1250, "stock": 3},
{"id": 13, "name": "Jute bag", "price": 199},
{"id": 14, "name": "Cotton saree", "price": 2400, "stock": 0},
{"id": 15, "name": "Steel tiffin", "price": 650, "stock": 9}
]
}
"""
@dataclass
class Product:
product_id: int
name: str
price: int
stock: int = 0
@property
def in_stock(self) -> bool:
return self.stock > 0
def parse_products(data: dict) -> list[Product]:
return [
Product(item["id"], item["name"], item["price"], item.get("stock", 0))
for item in data.get("products", [])
]
def main() -> None:
products = parse_products(json.loads(RESPONSE_TEXT))
print(products[2])
cheap = sorted(
(p for p in products if p.in_stock and p.price < 1000),
key=lambda p: p.price,
)
print("In stock under ₹1,000:")
for product in cheap:
print(f" {product.name:<16} ₹{product.price:,}")
value = sum(p.price * p.stock for p in products)
print(f"Stock value: ₹{value:,}")
if __name__ == "__main__":
main()
Exercise 5: Train status from a local API
Scenario: A railway app shows which trains leave a station and how late they are. What to do: Copy the starting code (a tiny train API that runs on your own computer), then:
- Write
get_json(url, params=None)that adds the encoded params, callsurllib.request.urlopenwithtimeout=5, and returns the decoded JSON. - Write
safe_get(url)that callsget_json, but onurllib.error.HTTPErrorprintsError <code>: <error text from the JSON body>and returnsNone. - In
main(): start the server, print every train fromPUNE(on timeor<n> min late), print the name of train12951from/api/trains/12951, printsafe_getof/api/trains/99999, then stop the server withserver.shutdown()andserver.server_close().
Starting data:
import json
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
TRAINS = [
{"number": "12127", "name": "Intercity Express", "from": "PUNE", "late_min": 0},
{"number": "11007", "name": "Deccan Express", "from": "PUNE", "late_min": 25},
{"number": "12951", "name": "Rajdhani Express", "from": "BCT", "late_min": 5},
]
class TrainHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
url = urllib.parse.urlparse(self.path)
query = dict(urllib.parse.parse_qsl(url.query))
status, data = 404, {"error": "Train not found"}
if url.path == "/api/trains":
found = [t for t in TRAINS if t["from"] == query.get("from", t["from"])]
status, data = 200, found
for train in TRAINS:
if url.path == f"/api/trains/{train['number']}":
status, data = 200, train
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args) -> None:
"""Stay quiet."""
def start_server() -> tuple[ThreadingHTTPServer, str]:
server = ThreadingHTTPServer(("127.0.0.1", 0), TrainHandler) # 0 = free port
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, f"http://127.0.0.1:{server.server_port}"
Sample output:
12127 Intercity Express on time
11007 Deccan Express 25 min late
Rajdhani Express
Error 404: Train not found
None
💡 Hint: server, base_url = start_server(). The error body can be read with json.load(error), just like a response. {train['name']:<18} lines up the names.
Show the solution to Exercise 5
"""Exercise 5: GET JSON from a tiny local train API with urllib.request.
The server below runs on your own computer, so no internet is needed.
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
import json
import threading
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# ---------- starting data: a tiny train-status API (given) ----------
TRAINS = [
{"number": "12127", "name": "Intercity Express", "from": "PUNE", "late_min": 0},
{"number": "11007", "name": "Deccan Express", "from": "PUNE", "late_min": 25},
{"number": "12951", "name": "Rajdhani Express", "from": "BCT", "late_min": 5},
]
class TrainHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
url = urllib.parse.urlparse(self.path)
query = dict(urllib.parse.parse_qsl(url.query))
status, data = 404, {"error": "Train not found"}
if url.path == "/api/trains":
found = [t for t in TRAINS if t["from"] == query.get("from", t["from"])]
status, data = 200, found
for train in TRAINS:
if url.path == f"/api/trains/{train['number']}":
status, data = 200, train
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args) -> None:
"""Stay quiet."""
def start_server() -> tuple[ThreadingHTTPServer, str]:
server = ThreadingHTTPServer(("127.0.0.1", 0), TrainHandler) # 0 = free port
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, f"http://127.0.0.1:{server.server_port}"
# ---------- end of starting data ----------
def get_json(url: str, params: dict | None = None):
if params:
url += "?" + urllib.parse.urlencode(params)
with urllib.request.urlopen(url, timeout=5) as response:
return json.load(response)
def safe_get(url: str):
"""Like get_json, but print the error and return None on 4xx/5xx."""
try:
return get_json(url)
except urllib.error.HTTPError as error:
print(f"Error {error.code}: {json.load(error)['error']}")
return None
def main() -> None:
server, base_url = start_server()
for train in get_json(base_url + "/api/trains", {"from": "PUNE"}):
late = train["late_min"]
status = "on time" if late == 0 else f"{late} min late"
print(f"{train['number']} {train['name']:<18} {status}")
print(safe_get(base_url + "/api/trains/12951")["name"])
print(safe_get(base_url + "/api/trains/99999"))
server.shutdown()
server.server_close()
if __name__ == "__main__":
main()
Exercise 6: School marks database
Scenario: A school stores students and their exam marks in two tables.
What to do: Using sqlite3 with ":memory:":
- Create
students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)andmarks (student_id, subject, score), and fill them withexecutemanyinsidewith conn:. - Print the average score per subject (rounded to 1 decimal, highest first) with
GROUP BY. - Print each student's total with a
JOIN, highest first. - Print how many papers are below
PASS_MARK(use?). - Kabir's Maths paper was re-checked:
UPDATEit to42, then print the failed count again.
Starting data:
STUDENTS = [(1, "Aarav"), (2, "Diya"), (3, "Kabir")]
MARKS = [ # (student_id, subject, score)
(1, "Maths", 88), (1, "Science", 72), (1, "English", 65),
(2, "Maths", 95), (2, "Science", 89), (2, "English", 91),
(3, "Maths", 35), (3, "Science", 58), (3, "English", 77),
]
PASS_MARK = 40
Sample output:
Average per subject:
English 77.7
Science 73.0
Maths 72.7
Total per student:
Diya 275
Aarav 225
Kabir 170
Failed papers: 1
Failed papers after re-check: 0
💡 Hint: SELECT subject, ROUND(AVG(score), 1) AS avg FROM marks GROUP BY subject ORDER BY avg DESC. For the update: WHERE student_id = ? AND subject = ?.
Show the solution to Exercise 6
"""Exercise 6: School marks database with sqlite3 (GROUP BY, JOIN, UPDATE).
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
import sqlite3
STUDENTS = [(1, "Aarav"), (2, "Diya"), (3, "Kabir")]
MARKS = [ # (student_id, subject, score)
(1, "Maths", 88), (1, "Science", 72), (1, "English", 65),
(2, "Maths", 95), (2, "Science", 89), (2, "English", 91),
(3, "Maths", 35), (3, "Science", 58), (3, "English", 77),
]
PASS_MARK = 40
def main() -> None:
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
conn.execute("""
CREATE TABLE marks (
student_id INTEGER NOT NULL REFERENCES students(id),
subject TEXT NOT NULL,
score INTEGER NOT NULL
)
""")
with conn:
conn.executemany("INSERT INTO students VALUES (?, ?)", STUDENTS)
conn.executemany("INSERT INTO marks VALUES (?, ?, ?)", MARKS)
print("Average per subject:")
for row in conn.execute(
"SELECT subject, ROUND(AVG(score), 1) AS avg FROM marks"
" GROUP BY subject ORDER BY avg DESC"
):
print(f" {row['subject']:<8} {row['avg']}")
print("Total per student:")
for row in conn.execute("""
SELECT students.name, SUM(marks.score) AS total
FROM students JOIN marks ON marks.student_id = students.id
GROUP BY students.id ORDER BY total DESC
"""):
print(f" {row['name']:<6} {row['total']}")
failed = conn.execute(
"SELECT COUNT(*) FROM marks WHERE score < ?", (PASS_MARK,)
).fetchone()[0]
print("Failed papers:", failed)
with conn: # re-check of Kabir's Maths paper
conn.execute(
"UPDATE marks SET score = ? WHERE student_id = ? AND subject = ?",
(42, 3, "Maths"),
)
failed = conn.execute(
"SELECT COUNT(*) FROM marks WHERE score < ?", (PASS_MARK,)
).fetchone()[0]
print("Failed papers after re-check:", failed)
conn.close()
if __name__ == "__main__":
main()
Exercise 7: Retry with backoff
Scenario: A price API sometimes answers "429 Too Many Requests". Your app should wait and try again, but not forever.
What to do: Write retry(func, attempts=4, base_delay=0.01) that calls func(). If it raises TemporaryError, print attempt <n> failed (<error>), waiting <delay> s, sleep, and try again. The wait doubles each time (0.01, 0.02, 0.04). After the last attempt, raise the error again. Test it with FlakyService(fail_times=2).get and with FlakyService(fail_times=10).get (catch the final error and print how many calls were made).
Starting data:
class TemporaryError(Exception):
pass
class FlakyService:
"""Fails with TemporaryError for the first fail_times calls."""
def __init__(self, fail_times: int) -> None:
self.fail_times = fail_times
self.calls = 0
def get(self) -> dict:
self.calls += 1
if self.calls <= self.fail_times:
raise TemporaryError("429 Too Many Requests")
return {"price": 2450}
Sample output:
Service that fails twice:
attempt 1 failed (429 Too Many Requests), waiting 0.01 s
attempt 2 failed (429 Too Many Requests), waiting 0.02 s
got {'price': 2450} after 3 calls
Service that is down:
attempt 1 failed (429 Too Many Requests), waiting 0.01 s
attempt 2 failed (429 Too Many Requests), waiting 0.02 s
attempt 3 failed (429 Too Many Requests), waiting 0.04 s
gave up after 4 calls: 429 Too Many Requests
💡 Hint: delay = base_delay * 2 ** (attempt - 1). Pass the method without calling it: retry(service.get), not retry(service.get()). A bare raise inside except raises the same error again.
Show the solution to Exercise 7
"""Exercise 7: Retry with exponential backoff (no network needed).
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
import time
class TemporaryError(Exception):
pass
class FlakyService:
"""Fails with TemporaryError for the first fail_times calls (given)."""
def __init__(self, fail_times: int) -> None:
self.fail_times = fail_times
self.calls = 0
def get(self) -> dict:
self.calls += 1
if self.calls <= self.fail_times:
raise TemporaryError("429 Too Many Requests")
return {"price": 2450}
def retry(func, attempts: int = 4, base_delay: float = 0.01):
"""Call func(). On TemporaryError wait base_delay, 2x, 4x ... and retry."""
for attempt in range(1, attempts + 1):
try:
return func()
except TemporaryError as error:
if attempt == attempts:
raise
delay = base_delay * 2 ** (attempt - 1)
print(f" attempt {attempt} failed ({error}), waiting {delay} s")
time.sleep(delay)
return None # not reached
def main() -> None:
print("Service that fails twice:")
service = FlakyService(fail_times=2)
print(" got", retry(service.get), "after", service.calls, "calls")
print("Service that is down:")
service = FlakyService(fail_times=10)
try:
retry(service.get)
except TemporaryError as error:
print(f" gave up after {service.calls} calls: {error}")
if __name__ == "__main__":
main()
Exercise 8: Expense repository
Scenario: A banking app sends your expenses as JSON. You import them into SQLite and query them through one class. What to do:
- Make a dataclass
Expensewithdate,category,note,amountandexpense_id(defaultNone). - Write a class
ExpenseRepository(conn)that creates anexpensestable (with anid INTEGER PRIMARY KEY) and has these methods:add_many(expenses): inserts all withexecutemany, returns how many.totals_by_category(): returns a dict{category: total}, highest first.search(text): returns theExpenseobjects whose note containstext(useLIKE ?).delete(expense_id): returnsTrueif a row was deleted, elseFalse.
- Import
RESPONSE_TEXT(Expense(**item)for each item), then print: the import count, the totals, each match ofsearch("thali")as#<id> <note> ₹<amount>, the result of the "tricky" search"' OR '1'='1",delete(2)twice, and the totals again.
Starting data:
RESPONSE_TEXT = """
[
{"date": "2026-07-01", "category": "food", "note": "Veg thali", "amount": 180},
{"date": "2026-07-01", "category": "travel", "note": "Metro card", "amount": 500},
{"date": "2026-07-02", "category": "food", "note": "Masala dosa", "amount": 90},
{"date": "2026-07-03", "category": "bills", "note": "Mobile recharge", "amount": 299},
{"date": "2026-07-03", "category": "food", "note": "Thali with sweet", "amount": 220}
]
"""
Sample output:
Imported: 5
Totals: {'travel': 500, 'food': 490, 'bills': 299}
#1 Veg thali ₹180
#5 Thali with sweet ₹220
Tricky search: []
Deleted #2: True
Deleted #2 again: False
Totals: {'food': 490, 'bills': 299}
💡 Hint: For LIKE, put the % signs in the value: ("%" + text + "%",). SQLite's LIKE ignores upper/lower case for English letters, so thali finds Thali. cursor.rowcount tells how many rows DELETE removed. The tricky search finds nothing, because ? keeps it as plain text.
Show the solution to Exercise 8
"""Exercise 8: ExpenseRepository: import API JSON into SQLite behind a class.
Run: python ex08.py (macOS/Linux: python3 ex08.py)
"""
import json
import sqlite3
from dataclasses import dataclass
RESPONSE_TEXT = """
[
{"date": "2026-07-01", "category": "food", "note": "Veg thali", "amount": 180},
{"date": "2026-07-01", "category": "travel", "note": "Metro card", "amount": 500},
{"date": "2026-07-02", "category": "food", "note": "Masala dosa", "amount": 90},
{"date": "2026-07-03", "category": "bills", "note": "Mobile recharge", "amount": 299},
{"date": "2026-07-03", "category": "food", "note": "Thali with sweet", "amount": 220}
]
"""
@dataclass
class Expense:
date: str
category: str
note: str
amount: int
expense_id: int | None = None
class ExpenseRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
self.conn.row_factory = sqlite3.Row
self.conn.execute("""
CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY,
date TEXT NOT NULL,
category TEXT NOT NULL,
note TEXT NOT NULL,
amount INTEGER NOT NULL
)
""")
def add_many(self, expenses: list[Expense]) -> int:
with self.conn:
self.conn.executemany(
"INSERT INTO expenses (date, category, note, amount)"
" VALUES (?, ?, ?, ?)",
[(e.date, e.category, e.note, e.amount) for e in expenses],
)
return len(expenses)
def totals_by_category(self) -> dict[str, int]:
rows = self.conn.execute(
"SELECT category, SUM(amount) AS total FROM expenses"
" GROUP BY category ORDER BY total DESC"
)
return {row["category"]: row["total"] for row in rows}
def search(self, text: str) -> list[Expense]:
rows = self.conn.execute(
"SELECT * FROM expenses WHERE note LIKE ? ORDER BY id",
(f"%{text}%",), # the % signs go in the value, not the SQL
)
return [
Expense(r["date"], r["category"], r["note"], r["amount"], r["id"])
for r in rows
]
def delete(self, expense_id: int) -> bool:
with self.conn:
cursor = self.conn.execute(
"DELETE FROM expenses WHERE id = ?", (expense_id,)
)
return cursor.rowcount == 1
def main() -> None:
repo = ExpenseRepository(sqlite3.connect(":memory:"))
expenses = [Expense(**item) for item in json.loads(RESPONSE_TEXT)]
print("Imported:", repo.add_many(expenses))
print("Totals:", repo.totals_by_category())
for expense in repo.search("thali"):
print(f" #{expense.expense_id} {expense.note:<16} ₹{expense.amount}")
print("Tricky search:", repo.search("' OR '1'='1"))
print("Deleted #2:", repo.delete(2))
print("Deleted #2 again:", repo.delete(2))
print("Totals:", repo.totals_by_category())
repo.conn.close()
if __name__ == "__main__":
main()
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
No timeout= on a request |
A dead server freezes your program forever | Always pass timeout=5 (or similar) |
| API key written in the code | It leaks when you share or push the code | Read it from os.environ |
Building a URL with + and raw values |
Spaces and & break the URL |
urllib.parse.urlencode(params) or params= in requests |
requests.get(...) without raise_for_status() |
A 404 or 500 looks like success | Call response.raise_for_status() |
data["phone"] on optional fields |
KeyError when the API leaves it out |
data.get("phone", "not given") |
| Retrying in a tight loop with no wait | Makes the rate limit worse, may get you blocked | Backoff: wait 2x longer each time; never retry 4xx except 429 |
f"... WHERE name = '{name}'" |
SQL injection, and breaks on D'Souza |
"... WHERE name = ?", (name,) |
("Pune") as the parameters |
That is a string, not a tuple | ("Pune",) with a comma |
| Forgetting to commit | Changes vanish when the program ends | Write changes inside with conn: |
Thinking with conn: closes it |
It only commits or rolls back | Call conn.close() at the end |
UPDATE/DELETE without WHERE |
Changes every row | Always write the WHERE first |
Quick recap
- A client sends an HTTP request (method, URL, headers, body); the server returns a status code, headers and a body, usually JSON.
- 2xx success, 3xx redirect, 4xx your mistake, 5xx the server's problem;
429means slow down. urllib.request.urlopen(url, timeout=...)+json.loadwork with no install; catchHTTPErrorbeforeURLError.requestsdoes the same with less code.- Read JSON with
[]for required keys and.get(key, default)for optional ones, then turn it into dataclasses. - Keep API keys in environment variables; retry temporary errors with backoff; cache answers that do not change often.
- SQL:
CREATE,INSERT,SELECT ... WHERE ... ORDER BY,UPDATE,DELETE, aggregates withGROUP BY, andJOINto combine tables. - In
sqlite3always use?placeholders,with conn:to commit,row_factory = sqlite3.Rowto read by name, andclose()at the end. - Put the SQL for a table in one repository class; ORMs and PostgreSQL come later.
Checklist
- I can name the parts of a URL and explain GET, POST, PUT and DELETE.
- I can tell what a status code means from its first digit.
- I can make a GET with query parameters and a POST with JSON using
urllib.request, with a timeout. - I can handle
HTTPError,URLErrorand timeouts. - I can read the
requestsversion of the same calls. - I can read nested JSON safely and turn it into dataclasses.
- I can create tables and write
SELECT,GROUP BYandJOINqueries. - I can use
sqlite3with?placeholders and explain SQL injection.