Module 3 โ Real-world I/Oยถ
๐งญ โ Data Science ยท ๐ Course home ยท Web Scraping โถ
Goal: Move beyond toy data. Make polite, retry-aware HTTP calls against live APIs and query a SQL database from Python โ the two ways real business data reaches your code (with an optional appendix for the API-less web: scraping).
Estimated time: 4โ6 hours of focused study.
Prerequisites: Modules 1โ2 (especially NB 4 โ dictionaries and JSON โ and NB 7 โ pandas; the ETL and SQL examples build DataFrames).
Public APIs Your databases
(NB 12 โ HTTP) โโโบ (NB 13 โ SQL/SQLite)
โ โ
โโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โผ
Now you can pull real data from anywhere โ
and appendix A1 covers pages with no API
(scraping + Firecrawl).
Notebooks at a glanceยถ
# |
Notebook |
โฑ Time |
Difficulty |
What youโll learn / build |
|---|---|---|---|---|
12 |
|
~45โ60 min |
Beginner / Intermediate |
GET/POST with |
13 |
|
~50โ70 min |
Beginner / Intermediate |
The six core SQL clauses, aggregations, JOINs, CTEs, and a window-function tour on an in-memory SQLite database โ plus when SQL beats pandas |
Optional appendix at a glanceยถ
Appendix |
Notebook |
โฑ Time |
Difficulty |
Focus |
|---|---|---|---|---|
A1 |
|
~50โ70 min |
Intermediate |
Optional, demo/reference style. DIY scraping with |
Notebook guidesยถ
12 ยท APIs, HTTP, and Real-World Data Fetching โ 12_apis_and_http.ipynbยถ
One question threads the whole notebook: โWhatโs the weather going to do this week?โ You start by asking the Open-Meteo API for the current temperature in Berlin, and every new idea โ status codes, headers, retries, pagination โ earns its keep by making that same weather question more robust. By the last section the pieces snap together into a real ExtractโTransformโLoad pipeline that pulls a 7-day forecast for four cities (Berlin, London, New York, Tokyo) into a tidy CSV. A second, fake API (JSONPlaceholder) is borrowed for two detours weather canโt demonstrate: POST and pagination.
The mental model throughout: talking to an API is like mailing a letter and waiting for the reply โ you format an envelope (method + URL + headers, plus a body for POST), requests is the courier, the server mails back a status code, headers, and body. The same patterns transfer directly to calling OpenAI, Anthropic, Stripe, Salesforce, or your internal data warehouse. Both APIs are free and keyless, and every networked cell degrades gracefully to a recorded response when there is no internet.
Learning objectives:
Send
GETandPOSTrequests with therequestslibraryRead HTTP status codes and handle errors gracefully
Add query parameters, headers, and bearer-token auth
Parse JSON responses into Python dicts and pandas DataFrames
Handle rate limits and flaky networks with retry + backoff, and paginate multi-page result sets
Build a small ETL pipeline that fetches API data and saves it locally
Sections:
The shape of every HTTP request
Setup
Your first GET request (incl. the request/response lifecycle, status codes, and headers up close)
HTTP status codes โ what the server is telling you
Headers, authentication, and
User-AgentPOST โ sending data to a server
Retry with exponential backoff
Pagination โ when one request isnโt enough
Putting it together โ a real ETL pipeline
Common pitfalls
Practice: 3 โ quick exercises ยท 4 ๐งช practice exercises (โญโโญโญ, incl. a Debug me ๐) ยท 4 ๐ง stretch exercises (โญโญโญ) ยท 1 ๐ bonus mini-project (a weekly weather dashboard built on the ยง9 fetch_forecast helper).
Files/datasets: Writes forecast.csv (city, date, max/min temperature, precipitation โ 7 days ร 4 cities). The copy shipped in this folder is the output of a sample run, so you can see what the pipeline should produce. No input files needed.
13 ยท SQL Fundamentals with pandas โ 13_sql_fundamentals.ipynbยถ
Every analyst job description asks for SQL, yet you can read most of the Python data-science internet without seeing a single SELECT. This notebook closes that gap. One dataset runs through everything: support_ops โ customer support across five channels (Email, Chat, Phone, Web Form, Social) where an AI bot automates part of the load, with monthly ticket volume, automation rate, latency, satisfaction, and cost. That table is the question machine for the whole lesson: which channels does the bot serve well, and which need help?
The data (60 channel-month rows, built inline with a seeded RNG so the notebook is self-contained) is pushed into a SQLite database that lives entirely in RAM โ SQLite ships with Python, so there is nothing to install. The mental model: a SQL query is an assembly line whose stations (WHERE, GROUP BY, HAVING, SELECT, โฆ) donโt run in the order you write them โ ยง5 shows the real logical order, which explains half of SQLโs confusing errors. Along the way you mirror queries in pandas and learn when each tool wins; the same SQL transfers (with minor syntax differences) to PostgreSQL, MySQL, BigQuery, and Snowflake.
Learning objectives:
Connect to a SQLite database from Python and create tables from a DataFrame
Write the six SQL clauses that cover ~95% of analytics work:
SELECT,FROM,WHERE,GROUP BY,ORDER BY,LIMITAggregate with
COUNT,SUM,AVG,MIN,MAX(and filter buckets withHAVING)Join two tables on a key, and break complex queries into readable CTEs (
WITH โฆ)Move data between SQL and pandas with
read_sqlandto_sqlDecide when SQL is the better tool than pandas (and vice versa)
Sections:
SQL in one slide
Setup โ load the data into SQLite (built inline, pushed in via
to_sql)Your first SELECT
WHERE โ filtering rows
Aggregations โ the part that earns its keep (the logical clause order,
HAVING)Grouping by multiple columns and time
JOINs โ bringing two tables together
CTEs โ making complex queries readable
SQL vs pandas โ when to use which
Tiny tour of window functions
Cleaning up
Practice: 4 โ quick exercises (plus a ๐ฎ predict-the-output checkpoint) ยท 5 ๐งช practice exercises (โญโโญโญ, incl. a Debug me ๐) ยท 4 ๐ง stretch exercises (โญโญโญ) ยท 1 ๐ bonus mini-project (a SQL-driven mini report combining a CTE with a JOIN).
Files/datasets: Nothing on disk โ sqlite3.connect(":memory:") creates the database in RAM, holding support_ops plus a channel_meta lookup table (team leads, launch years) and a tiny budgets table for the JOIN section. The notebook shows sqlite3.connect("ops.db") as the one-line change that would persist it to a file.
Appendix guideยถ
A1 ยท Web Scraping & Firecrawl โ A1_web_scraping_firecrawl.ipynbยถ
Notebook 12 pulled data from a clean JSON API โ but most of the web has no API, and the data you want is trapped in HTML meant for human eyes. This optional, reference-style appendix has two halves: do it yourself (requests + BeautifulSoup, the rules of the road โ robots.txt, ToS, rate limits, GDPR/PII โ and the four polite-scraper habits: identify, throttle, cache, retry), then let a service do the hard part โ Firecrawl, an API that turns any URL (including JavaScript-heavy, anti-bot pages) into clean, LLM-ready markdown or structured JSON in one call, the modern way to feed a RAG pipeline or an agent.
Everything runs offline: the hands-on BeautifulSoup cells parse a local HTML fixture (a mock bookshop catalogue page) instead of fetching a live site, and the Firecrawl cells use a small built-in mock that mimics the v2 SDK surface โ install firecrawl-py and set FIRECRAWL_API_KEY to swap in the real service. The structured-extraction demo validates Firecrawlโs JSON output with Pydantic (falling back to a dataclass if Pydantic isnโt installed), and real SDK calls (scrape / crawl / map / search) are shown as commented reference code.
Sections:
When to scrape โ and the rules you donโt break
The anatomy of a scrape
Respect
robots.txtPolite scraping โ the four habits
Where DIY scraping hurts
Firecrawl โ the LLM-ready web API (incl. structured extraction into typed JSON)
Choosing your approach
Practice: 3 โ quick exercises ยท 2 ๐งช exercises (unrated โ appendices favour demo over drill) ยท no stretch exercises or mini-project.
Files/datasets: None โ the HTML fixture and the Firecrawl mock live inline in the notebook.
How these notebooks workยถ
Every notebook runs 100% offline. NB 12 talks to two free, keyless public APIs (Open-Meteo and JSONPlaceholder) when you have internet, and every networked cell wraps its call in try/except with a graceful fallback to a recorded response โ plus โoffline proofโ cells that model the whole request/response lifecycle with plain dicts. NB 13 never touches the network at all (in-memory SQLite), and A1 scrapes a local HTML fixture and mocks the Firecrawl SDK. Each lesson opens with a Colab badge and a metadata line (estimated time, difficulty), then follows the course rhythm: โ Quick exercise (~2 min) checkpoints with collapsible ๐ก solutions, end-of-lesson ๐งช practice exercises (โญ-rated, including a โDebug me ๐โ), ๐ง stretch exercises, and a ๐ bonus mini-project in the core lessons.
Where nextยถ
โ Module 4 โ Web Scraping (../04_webscraping/) โ get data off the web politely when thereโs no API, or
โ Module 5 โ Machine Learning (../05_machine_learning/17_sklearn_basics.ipynb)
๐ Finished this module? Test yourself with the Module 3 quiz โ five questions, ~10 minutes.