DS 227 · Week 4

Data Scraping II

APIs, dynamic pages, and scraping ethics: fetching data over the network, and determining what may be collected.

Knowledge Discovery in Data · University of the Philippines Cebu

Outline

Three routes to external data

Previous session

From scraping pages to using APIs

Last week the portal's calendar was fetched with requests and 13 rows were extracted from its tags. The method worked but was fragile. This week covers methods that avoid reading HTML entirely.

Scraping (last week)

Fetch HTML built for reading, locate the right class, and depend on the page not changing.

Using an API

Request data from a web API, a URL built for programs, and receive structured data without tags.

Guideline

Check for an API before scraping a page; an API is faster, more robust, and fairer.

About the tool

requests made HTTP readable in 2011

2000

REST

Roy Fielding’s PhD thesis (UC Irvine) describes the style most web APIs follow.

2011

requests

Kenneth Reitz releases it on 14 February: “HTTP for Humans”.

2019

New home

Reitz hands the project to the Python Software Foundation.

SourceWikipedia: Requests; Wikipedia: REST; requests.readthedocs.io

About the tool

How widely requests is used

SourceDownloads: pypistats.org (requests, numpy, pandas), without mirrors, retrieved 11 Oct 2026; Wikipedia: Requests

Key terms · 1 of 2

Eight terms for querying an API (Part A)

API

A web address built for programs, not people: ask in a fixed way, get data back in a fixed shape.

e.g. /api/demo on this portal

endpoint

One specific address of an API. Each endpoint serves one kind of data.

e.g. /api/demo/sales/7 gives sale number 7

request / response

The message a program sends to a server (“GET me this”) and the reply that comes back.

e.g. r = requests.get(url) sends one; r holds the reply

status code

The three-digit number on every response: 2xx success, 4xx a client error, 5xx a server error.

e.g. 200 OK · 404 not found · 429 too many requests

JSON

Text written like Python lists and dictionaries; the usual format of API replies.

e.g. {"item": "kape", "qty": 2}

object / array

JSON’s two containers: an object { } holds named values (a dict); an array [ ] holds values in order (a list).

e.g. [{"id": 1}, {"id": 2}] is an array of two objects

key / value

Inside an object, the key is the name in quotes; the value is the data after the colon.

e.g. in "qty": 2 the key is qty, the value 2

null

JSON’s word for “nothing recorded here”. Python turns it into None.

e.g. "closed_on": null becomes None

Key terms · 2 of 2

Ten terms for responsible requests (Parts A–C)

query parameter

A setting after ? in the address that narrows the request.

e.g. /api/demo/sales?barangay=Lahug

pagination

A long answer split into pages, requested as page 1, then 2… until there is no next page.

e.g. "page": 1, "pages": 3, "next": …

header

A labelled note that travels with a request or response, outside the data itself.

e.g. Retry-After: 60

API key

A password-like code that tells the API who is asking; often raises the rate limit.

e.g. X-API-Key: latarak-demo

rate limit

The maximum number of requests an API accepts from one client per minute; exceeding it returns a 429.

e.g. 12 a minute on the demo API without a key

dynamic page

A page whose data is filled in after it loads, so the HTML fetched by code is nearly empty.

e.g. the browser shows 40 rows; find_all finds 0

JavaScript rendering

The browser running the page’s own program (JavaScript) to fetch data and draw it.

e.g. visible in Inspect, missing from View Source

robots.txt

A plain-text file at a site’s root listing where automated programs should not go.

e.g. Disallow: /private/

terms of service

The site’s written rules of use. They can forbid scraping even of public pages.

e.g. “no automated collection” clauses

polite scraping

Collecting slowly and openly: a delay between requests, and a User-Agent header identifying the requester.

e.g. time.sleep(1)

Part A

APIs

The same request–response exchange, with an answer built for programs.

Week 3 showed how a program requests a page from a server and receives HTML. This part keeps that exchange but replaces the HTML with data built for programs: JSON from an API.

Same model, new payload

The server responds in JSON

Client program requests / pandas API server serves data, not pages GET /users?city=Cebu → "send me records" 200 OK + JSON ← "here they are"
Basic request

Request, then status check

The requests library (ready-made code, week 3) handles the networking. The remaining task is last week's guideline: status first, body second.

Why timeout=30

Network requests can stall. Without a timeout the notebook waits indefinitely; with one, an unresponsive server produces an error that can be handled.

import requests r = requests.get( "https://jsonplaceholder.typicode.com/users", timeout=30) print(r.status_code) # 200 data = r.json() # body, parsed print(len(data)) # 10
  • import requestsload the requests library, which sends web requests
  • r = requests.get("…/users", timeout=30)send a GET request to that address and keep the whole reply in r; give up after 30 seconds
  • r.status_code → 200the status code: 200 means “OK, data returned”
  • data = r.json()read the reply’s body and turn its JSON text into Python lists and dicts
  • len(data) → 10the body was a list of 10 records: ten users
Payload

JSON is text that looks like Python

Curly braces, square brackets, key–value pairs. One r.json() call converts the text into familiar dicts and lists.

Definitions

JSON
JavaScript Object Notation: a text format programs use to send each other data
object { }
named values in curly brackets; becomes a Python dict
key / value
in "id": 1 the key is the name "id", the value is 1
array [ ]
values in order in square brackets; becomes a Python list. Here: two objects
nested
a value that is itself an object: "address": {"city": …}
[ { "id": 1, "name": "Leanne Graham", "email": "[email protected]", "address": { "city": "Gwenborough" } }, { "id": 2, "name": "Ervin Howell", … } ]

No tags, no tree navigation

Compared with last week’s nested <li> markup, the structure here is the data.

Type mapping

Python equivalents of JSON types

r.json() is the translator. After it runs, no JSON remains in the program, only ordinary Python objects (values). JSON’s null means “no value recorded” and becomes Python’s None.

JSON is a shipping format every program can read, and r.json() unpacks the parcel into Python’s own containers: a dict (key → value, like a phone book) or a list (items in order).

JSONPythonExample
object { }dictu["name"]
array [ ]listdata[0]
stringstr"Cebu"
numberint / float27.5
true / falseTrue / False"open": true
nullNoneNone: a gap that must be handled
Sandbox

An API built for this class

A sandbox is a safe place to practise, where mistakes cost nothing. Public APIs throttle clients (slow them down), move, or shut down. This one runs on the same server as this deck, and heavy use is permitted.

portal.latarak.com/api/demo

import requests BASE = "https://portal.latarak.com" r = requests.get(BASE + "/api/demo", timeout=30) print(r.status_code) # 200
  • BASE = "https://portal.latarak.com"a variable holding the site’s address, typed once and reused on every slide
  • BASE + "/api/demo"+ joins two pieces of text into one full address; /api/demo is the endpoint

Fictional data, real behaviour

Fictional sari-sari store sales, but the status codes, pagination, errors and rate limits behave as in a real API.

Discovery

Self-describing APIs

Before reading any docs (the API’s instructions), request the root endpoint: the top address, /api/demo, with nothing after it. Well-built APIs describe themselves.

First step

It names every endpoint, the auth header, and the rate limit: the three items needed before writing a loop.

d = r.json() # the reply, as a Python dict print(d["name"]) for name in d["endpoints"]: print(name) print(d["auth"]) print(d["rate_limit"]) Latarak Demo API GET /api/demo/barangays GET /api/demo/sales GET /api/demo/sales/{id} optional header X-API-Key: latarak-demo raises your rate limit 12/min anonymous, 200/min with the demo key
  • d["name"]look up one key of the dict and get its value
  • for name in d["endpoints"]:endpoints is a dict inside the dict; looping over it gives its keys, one endpoint per line
  • the outputthree endpoints, an optional key sent as a header, and the rate limit: 12 requests a minute without the key
Status codes

APIs use the same status codes

A status code is the three-digit number on every response saying how it went.

Two concern the client: the key (401, new) and the request rate (429, deferred from last week's table).

CodeMeansAction
200OKParse the JSON
400Bad request (a setting in the request is not allowed)Read the error, fix the request
401No / bad keyCorrect the credentials
404No such recordNothing to parse — handle it
429Too many requestsSlow down, wait, retry
500Server brokeServer-side fault; retry later

The first digit works like the stamp on a returned parcel: 2 = delivered, 4 = a problem with the sender’s request (wrong address, too many parcels today), 5 = a fault at the depot.

Single record

Fetching a single record

Most APIs provide a collection endpoint (many records) and a single-item endpoint (one record). The id goes in the path (the part of the address after the site name, here /api/demo/sales/7), not in a parameter.

r = requests.get(BASE + "/api/demo/sales/7") print(r.json()) {'barangay': 'Mabolo', 'date': '2026-09-07', 'id': 7, 'item': 'noodles', 'price': 13, 'qty': 2, 'total': 26}

Dict, not list

A single-item endpoint returns one object. r.json()["total"] works directly — no indexing first. The single quotes show it is already a Python dict, not JSON text.

Missing records

Requesting a nonexistent id (9999)

There are only 60 sales. A good API does not crash or return an empty 200; it returns 404 (“not found”) with an explanation.

r = requests.get(BASE + "/api/demo/sales/9999") print(r.status_code) # 404 print(r.json()) {'error': 'No sale with id 9999.', 'hint': 'Valid ids are 1..60.'}

Read the body on failure

The hint ("Valid ids are 1..60") describes the API’s valid inputs, and is frequently overlooked.

Status codes

Four requests, four status codes

All four are requests to the demo API. The code indicates the next step before any of the body is read.

400 is new: “bad request”. The address exists, but a setting in the request (here, limit=99) is not allowed.

# same API, four different requests /api/demo/sales/7 200 /api/demo/sales/9999 404 /api/demo/sales?limit=99 400 /api/demo/nope 404

Branching on the code

200 parse · 400 correct the request · 404 record does not exist · 429 reduce the rate.

JSON to rows

Converting a list of records to a DataFrame

Each JSON object becomes a row; each key becomes a column. The result is an ordinary pandas DataFrame, as in earlier weeks.

Selecting columns

The column list [["id", "name", "email"]] is a selection; adding a key to it keeps one more column.

import requests, pandas as pd people = requests.get(URL, timeout=30).json() df = pd.DataFrame(people)[["id", "name", "email"]] print(df.shape) # (10, 3)
  • URLthe users address from the earlier slide, kept in a variable
  • pd.DataFrame(people)build a DataFrame (pandas’ table of rows and named columns): each dict becomes a row, each key a column
  • [["id", "name", "email"]]keep only these three columns: the outer brackets select, the inner list names them
  • df.shape → (10, 3)the table’s size: 10 rows (users) and 3 columns
Nested values

Values that are objects

A user's address is itself a dict: a dict inside a dict is called nested. To flatten it into a column, two keys are applied in sequence before building the frame.

Optional lab extension

The lab builds this name + city table using chained keys only.

person["address"] # {'city': 'Gwenborough', …} person["address"]["city"] # 'Gwenborough' rows = [{"name": p["name"], "city": p["address"]["city"]} for p in people]
  • personone record from the list, e.g. people[0]
  • person["address"]its value is a whole dict, not a single piece of text
  • person["address"]["city"]two keys in a row: open address, then take city from inside it
  • rows = [ {…} for p in people ]a list comprehension: a one-line loop that builds one small dict per person and collects them all in a list
Query parameters

Parameters filter on the server side

A query parameter is a setting added after ? in the address, like ?postId=1; together they form the query string. Passing a dict to params= makes requests build the query string, correctly escaped (special characters safely coded).

Why not write it by hand

Spaces, symbols and Unicode all need escaping. params= handles this correctly; manually concatenated URLs eventually fail.

r = requests.get( "…/comments", params={"postId": 1}, timeout=30) print(r.url) # …/comments?postId=1 print(len(r.json())) # 5
  • params={"postId": 1}the filter as a dict: key = the parameter’s name, value = the requested value
  • r.url → …/comments?postId=1the full address requests actually sent: it added ?postId=1 automatically
  • len(r.json()) → 5the server sent back only the comments on post 1: five of them
Filtering

Server-side filtering

Downloading all 60 rows to keep 12 wastes the provider’s bandwidth (the data they pay to send) and the analyst’s time. The request should specify only what is needed.

Reading the output

d["total"] → 12
sales in Talamban altogether
d["pages"] → 3
pages needed at 5 sales per page, the default
d["results"]
this page’s records: a list of dicts
r = requests.get(BASE + "/api/demo/sales", params={"barangay": "Talamban"}) d = r.json() print(d["total"], d["pages"]) # 12 3 print(d["results"][0]) {'barangay': 'Talamban', 'date': '2026-09-03', 'id': 3, 'item': 'sardinas', 'price': 28, 'qty': 3, 'total': 84}

params= instead of manual URLs

Passing a dict lets requests encode spaces and symbols correctly. Building the URL by hand is a common cause of unexplained 400s.

Pagination

One page per request

Pagination means the API splits a long answer into pages and sends one page per request. Each reply states the current page, the number of pages, and the location of the next one. On the last page next is None (JSON null).

Shopping-site search results, with 5 items per screen and a “Next” button that is pressed until it disappears.

for page in [1, 2, 3]: d = requests.get(BASE + "/api/demo/sales", params={"barangay": "Talamban", "page": page}).json() print(page, len(d["results"]), d["next"] is None) 1 5 False 2 5 False 3 2 True
  • for page in [1, 2, 3]:send the request three times, once per page number
  • "page": pagethe query parameter that picks which page comes back
  • len(d["results"])records on this page: 5, 5, then the last 2 (12 = 5 + 5 + 2)
  • d["next"] is NoneTrue only on page 3: no next page, so all records have been collected
Invalid requests

An informative 400 response

A request for 99 rows a page is refused, but the API states the cap and how to raise it: send a header (a labelled note that travels with the request, outside the address) carrying an API key (a password-like code that says who is asking).

requests.get(BASE + "/api/demo/sales", params={"limit": 99}) # 400 {"error": "limit is capped at 20 on your tier.", "hint": "Send X-API-Key: latarak-demo to raise the cap to 50."}

The remedy is in the response

A 400 body that only says "Bad Request" indicates a poorly designed API. This one names the limit and the header that raises it.

Review question

Interpreting a 429 response

A loop of API calls suddenly starts returning 429. What does the server indicate?

A · The record doesn't exist
B · The key is wrong
C · Requests are too frequent; slow down
D · The server crashed

C — too many requests.

A 429 is a rate limit: the server is protecting itself from excessive requests. The client should pause, add a delay between calls, and retry later; continuing regardless leads to a ban.

Real dataset

Public spending data

The same methods and status codes apply to 34,079 real DPWH (Department of Public Works and Highways) flood control projects, 2016–2026, which are public record.

Definitions

d["source"]["licence"]
two keys in a row: the source dict, then its licence
CC0 / public domain
free for anyone to reuse; no permission needed
mirror
a copy of a dataset kept on another site
403
“Forbidden”: the server understood and refuses; here it refuses scripts
BASE = "https://portal.latarak.com" r = requests.get(BASE + "/api/flood", timeout=30) d = r.json() print(d["rows"], d["source"]["licence"]) 34079 CC0-1.0 (public domain)

Where it comes from

BetterGov.ph’s mirror of the DPWH transparency portal. CC0 (public domain), free to use. The DPWH site itself returns 403 to scripts, so it is not used for live demonstration.

Documentation

A data-quality warning from the API

The discovery (root) endpoint carries a data_quality_warning. Most APIs do not, but when one does, reading it prevents publishing a false claim.

Definitions

field
another word for a column (or a JSON key)
upstream export
the original file this API copied its data from
not populated
never filled in: the 0 is a placeholder, not a measurement
print(d["data_quality_warning"]) {'field': 'amount_paid', 'note': "This field is 0 on EVERY row, here and in the upstream export. It is not populated. It does NOT mean these projects were unpaid. Anyone reporting 'completed but never paid' from this column would be wrong."}

Note

The following slides deliberately ignore this warning to show the consequence.

Single project

A single contract, in full

Every project has a contract id and represents real funds, a real contractor, and a real location.

₱279.8 million

One storm surge protection structure in Donsol, Sorsogon: the scale of a single row in this file.

r = requests.get(BASE + "/api/flood/projects/22F00136") p = r.json() for k in ("status", "budget", "contractor", "region"): print(k, "=", p[k]) status = Completed budget = 279839557.31 contractor = CENTERWAYS CONSTRUCTION AND DEVELOPMENT INC. (34105) region = Region V
  • …/projects/22F00136a single-item endpoint: the contract id goes in the path
  • for k in ("status", …):repeat for each of the four key names in the brackets
  • print(k, "=", p[k])print the key’s name, an equals sign, and that key’s value from the record
Filtering

Filtering on the server

34,079 rows is small enough to download, but the practice matters: server-side filtering transfers kilobytes instead of megabytes.

Server-side filtering is asking a librarian for three specific books instead of carrying the whole library home to search it.

The output: 4,424 completed Region III projects; at limit 3 per page that is 1,475 pages.

r = requests.get(BASE + "/api/flood/projects", params={"region": "Region III", "status": "Completed", "limit": 3}) d = r.json() print(d["total"], d["pages"]) 4424 1475

params= handles the space

"Region III" contains a space. requests encodes it; a hand-built URL produces an unexplained 400.

Pagination loop

Region III in 55 requests

Same pattern as the Talamban pages: keep asking until next is None. On real data it collects five thousand rows without computing page numbers in advance.

The API key

Without it, limit: 100 is refused with a 400: anonymous callers get 25 rows a page and 20 requests a minute, so this loop would need 217 requests and hit a 429. With the key: 100 a page, 200 a minute.

KEY = {"X-API-Key": "latarak-demo"} rows, page = [], 1 while True: d = requests.get(BASE + "/api/flood/projects", params={"region": "Region III", "limit": 100, "page": page}, headers=KEY).json() rows += d["results"] if not d["next"]: break page += 1 print(page, len(rows)) 55 5412
  • headers=KEYsend the API key as a header, so 100 rows a page are allowed
  • while True: … breakrepeat for ever, until break jumps out of the loop
  • rows += d["results"]add this page’s records to the growing list
  • if not d["next"]: breakif there is no next page (None), stop; otherwise page += 1 requests the next
  • 55 541255 pages fetched, 5,412 projects collected
Result

₱267.7 billion in one region

With five thousand rows in a DataFrame, the first substantive question can be answered.

  • pd.DataFrame(rows)the list of 5,412 dicts becomes a table, one row per project
  • df["budget"].sum() / 1e9add up the budget column, divide by a billion (1e9 = 1 with 9 zeros)
  • round(…, 1) → 267.7keep one decimal: ₱267.7 billion
  • .value_counts()count how many rows have each status, biggest first
  • Name: count, dtype: int64the result is named count and holds whole numbers
import pandas as pd df = pd.DataFrame(rows) print(round(df["budget"].sum() / 1e9, 1)) 267.7 print(df["status"].value_counts()) status Completed 4424 On-Going 822 For Procurement 111 Not Yet Started 51 Terminated 4 Name: count, dtype: int64
Apparent finding

An apparent anomaly

comp = df[df["status"] == "Completed"] print(len(comp)) 4424 unpaid = comp[comp["amount_paid"] == 0] print(len(unpaid)) 4424 # every single one print(round(unpaid["budget"].sum() / 1e9, 1)) 201.1 # billion pesos
  • df[df["status"] == "Completed"]a boolean filter: keep only the rows where the test is True
  • comp["amount_paid"] == 0True for each completed project whose amount_paid is 0

₱201 billion of completed work recorded as unpaid

All 4,424 finished projects in this one region show nothing paid out.

At this point the conclusion appears obvious. It is also the point at which error is most likely.

Verification

Checking the column before the claim

Before anything is written, the simplest check applies: whether this column ever contains any other value.

.unique() lists each different value once. [0.] is an array (a NumPy list of numbers) holding a single value, 0.0: the column never says anything but zero.

print(df["amount_paid"].unique()) [0.] # every row in the region. and nationally: # 0 non-zero values across all 248,220 rows # of the source export.

An unpopulated field, not evidence

amount_paid is not populated in this export. It says nothing about whether anyone was paid, so the ₱201B finding is unsupported.

Guideline

Analysis of the near error

1 · The finding was real

The code was correct. The filter was correct. The sum was correct. Every number on the previous slide is true.

2 · The meaning was not

“Zero in a column” and “zero pesos paid” are different claims. The data cannot distinguish them; the analyst must.

3 · Real firms are named

Publishing this would have accused named companies of something that never happened — on evidence that was an empty column.

A missing value (nothing was recorded) and a zero look identical in a spreadsheet. The meaning of a column must be established before it is interpreted.

Exercise · 8 min

Querying the demo API

Open the API playground (/api-playground on the portal: a page that sends requests on click) or a notebook. Each task needs one request and no key.

Tasks

  1. Fetch /api/demo/barangays and count them.
  2. Fetch sale id=42; record its item and total.
  3. Filter sales to barangay=Lahug; count the rows.
  4. Request limit=99; record the status and the body’s message.

Answers

5 barangays · id 42 is load, total 40 · Lahug has 12 rows · limit=99 gives 400 with the cap and the header to lift it.

Break — 10 minutes

Next: pages that load their data dynamically, and the ethics of collecting it.

Part B

Dynamic pages

When the fetched HTML differs from the displayed page.

APIs and static pages are now covered. This part adds a third case: pages that fill themselves in after loading, and a one-minute test to identify them.

Symptom

Visible data, empty scrape result

The page is fetched and parsed, and find_all returns nothing, although the data is visible on screen. Nothing is broken: the page is dynamic.

Definitions

dynamic page
a page whose data is filled in after it loads
JavaScript
the programming language that runs inside web pages, in the browser
JavaScript rendering
the browser running that code to fetch the data and draw it
find_all
week 3’s BeautifulSoup search: every tag that matches
soup = BeautifulSoup(r.text, "html.parser") rows = soup.find_all("li", class_="listing") print(len(rows)) # 0 ← but the browser shows 40!

Explanation

The server sent a nearly empty shell plus JavaScript. The browser ran the script, which fetched the data and built the page after the scraper’s snapshot.

Diagnosis

Two views of the same page

Hidden APIs

The data source of dynamic pages

The source is almost always an API the site built for itself. In DevTools → Network, filtering by Fetch/XHR and reloading shows the JSON arriving.

Definitions

Network tab
the DevTools panel listing every request the page makes
Fetch/XHR
the filter showing only background data requests made by the page’s JavaScript
hidden API
an API the site built for its own pages: not advertised, but reachable

1 · Watch the traffic

Each row in the Network tab is a request the page made while building itself.

2 · Find the JSON call

Click a Fetch/XHR row and preview the response; one of them holds the data in clean form.

3 · Call it directly

Copy that URL into requests.get(); the task is then the same as Part A, with no HTML.

Browser automation

Last resort: automating a real browser

Browser automation means a program controls a real browser. Tools such as Selenium and Playwright (Python libraries) run an actual browser from Python: the JavaScript executes, the page builds, and then the tree is read.

Hiring an assistant to open each page, wait for it to load and copy the screen, which always works but is slow and needs a desk (memory) per assistant.

Advantage

The program sees exactly what a user sees, on any page, however dynamic.

Cost

A whole browser per script: slow, memory-hungry, fragile to site redesigns.

In this course

It is a last resort. The hidden-API method usually suffices, and this week's lab needs neither.

Decision path

Cheapest method first

1

Documented API

Use it: cleanest data, clearest rules; Part A suffices.

2

Data in View Source

Static page: requests + BeautifulSoup, as last week.

3

Hidden API in Network tab

Call the site's own JSON endpoint directly.

4

Otherwise

Browser automation: powerful, heavy, last resort.

Summary

Choosing a method

SituationMethodReason
There is a documented APIAPI Clean JSON, paginated, stable. The first option to check.
Data is in the page sourcerequests + parse Last week’s skill. Cheap, but breaks when markup changes.
Page is empty until JS runsfind the hidden API Open DevTools → Network to find the page’s data request.
Genuinely nothing else worksdrive a browser Slow, heavy, brittle. The last resort, not the first.
Part C

Scraping ethics

Access does not imply permission to collect.

Parts A and B covered three ways to obtain data. This part concerns request rate, identity, and permission: rate limits, keys, robots.txt, terms of service and personal data.

Rate Limits

Observing a rate limit

A rate limit is the maximum number of requests an API accepts from one client in a time window. The demo API allows 12 requests a minute anonymously; a loop of 15 deliberately exceeds it.

Not a code error

A 429 means the request was valid but too many were sent. Retrying immediately makes it worse.

for i in range(15): r = requests.get(BASE + "/api/demo/barangays") print(r.status_code, end=" ") 200 200 200 200 200 200 200 200 200 200 200 200 429 429 429
  • for i in range(15):repeat the indented lines 15 times
  • print(r.status_code, end=" ")print each code followed by a space instead of a new line
  • twelve 200s, then 429the first 12 requests this minute are served; numbers 13, 14 and 15 are refused
Retry-After

The server specifies the waiting time

The sleep time should not be guessed. Retry-After is a response header giving the number of seconds the server requires; the client should honour it.

  • r.headers["Retry-After"]read one header of the response; it arrives as text, "60"
  • int(…)turn that text into the number 60
  • time.sleep(60)pause the program for 60 seconds, then retry
print(r.status_code) # 429 print(r.headers["Retry-After"]) # 60 print(r.json()) {'error': 'Too many requests — slow down.', 'hint': "You get 12 requests/min on the 'anon' tier. Send header X-API-Key: latarak-demo for 200/min.", 'retry_after': 60}

Polite retry

if r.status_code == 429: time.sleep(int(r.headers["Retry-After"])) then retry. This is well-behaved scraper behaviour.

Review question

Responding to Retry-After

A request returns 429 with Retry-After: 36. What should the code do?

A · Retry immediately
B · Sleep 36 seconds, then retry
C · Give up and raise an error
D · Switch to a different endpoint

B — wait exactly as long as the server specified.

Retrying immediately worsens the problem and can lead to a block. The server specified the delay; any other value is a guess.

API keys

An API key raises the limit

Same request, one extra header, and the limit goes from 12/min to 200/min. A key lets a site identify the client.

r = requests.get( BASE + "/api/demo/barangays", headers={"X-API-Key": "latarak-demo"}) print(r.status_code) # 200 # same second, same endpoint — the key is # the only difference
  • headers={…}send one header with the request: its name is X-API-Key, its value is the key
  • 200the same second that gave 429 without a key now succeeds

Protecting real keys

The demo key is public and harmless. A real key belongs in an environment variable (a setting stored outside the code, e.g. in Colab Secrets); a key pasted into a notebook tends to end up on GitHub.

robots.txt

robots.txt: pages a site excludes

robots.txt is a plain-text file where a site lists what automated programs may not fetch. Nearly every site publishes one at /robots.txt. It is not a lock but a posted request. Honest crawlers (programs that visit pages automatically) read it first and comply.

Interpretation

"Everyone: stay out of /private/ and /search, and pause 10 seconds between requests."

# https://example.com/robots.txt User-agent: * Disallow: /private/ Disallow: /search Crawl-delay: 10 User-agent: Googlebot Allow: /
  • User-agent: *the rules below are for every program (* = everyone); a user agent is a program’s name tag
  • Disallow: /private/do not fetch any address that starts with /private/
  • Crawl-delay: 10wait 10 seconds between requests
  • User-agent: Googlebot / Allow: /Google’s crawler may fetch everything
Request rate

Request loops load servers

A tight loop of requests is indistinguishable from an attack. A small pause (a delay) keeps the scraper courteous and prevents bans.

If a 429 still occurs

Stop, wait longer, and re-read the API's documented limits. Retrying instantly makes it worse.

import requests, time for i in [1, 2, 3]: u = requests.get(f"…/users/{i}", timeout=30).json() names.append(u["name"]) time.sleep(0.3) # be polite
  • for i in [1, 2, 3]:fetch users 1, 2 and 3, one request each
  • f"…/users/{i}"an f-string: {i} is replaced by 1, then 2, then 3
  • names.append(u["name"])add each name to a list names made before the loop
  • time.sleep(0.3)wait 0.3 seconds before the next request
Polite Scraping

Slow, identified requests

Polite scraping means collecting the way the site owner would accept: a delay between requests, and a User-Agent header that names the program and gives a contact address.

The difference between a stranger trying every door at night and a visitor who knocks once, gives a name, and waits.

Reason for identification

Without it, requests introduces itself only as python-requests/ plus a version number. With a name and an email, a concerned site owner can make contact instead of blocking the scraper.

import requests, time HEADERS = {"User-Agent": "ds227-lab ([email protected])"} for page in [1, 2, 3]: r = requests.get(BASE + "/api/demo/sales", params={"page": page}, headers=HEADERS, timeout=30) print(page, r.status_code) time.sleep(1) # one request per second print(r.request.headers["User-Agent"]) 1 200 2 200 3 200 ds227-lab ([email protected])
  • HEADERS = {"User-Agent": …}the identification: the program’s name plus a contact address
  • headers=HEADERSsend that header with every request
  • time.sleep(1)the delay: wait one second before the next request
  • r.request.headers[…]what was actually sent: the server received the identification
Credentials

A key identifies its owner; protect it like a password

Named Entities

Some contractors are marked REVOKED

A licence is a contractor’s government permit to build; REVOKED means it was cancelled. The source encodes licence status in the contractor name. It is public record, but it is not a verdict on any single project.

r = requests.get(BASE + "/api/flood/contractors", params={"limit": 4}) for c in r.json()["results"]: print(c["projects"], c["licence_revoked"]) 876 False # "Unknown" — missing contractor 345 True # ST. TIMOTHY CONSTRUCTION 306 False # LEGACY CONSTRUCTION 283 True # ALPHA & OMEGA GEN. CONTRACTOR

What REVOKED does not indicate

When it was revoked, why, or whether it relates to these projects. It is a status at export time. Reporting it as guilt repeats the error of the ₱201B finding.

Before publication

Four checks before publication

CheckReason
The meaning of the column Empty, zero, and “not applicable” look identical once summed.
Whether a missing value explains the result The most dramatic findings are usually data problems, so this is checked first.
Who is named, and whether they can respond A company in a chart is a party to the story and has a right to respond.
Whether the analyst would put their name to the number If not, it is not ready, however good the chart looks.
Legal and ethical checks

Three questions before any real scrape

Exercise · 5 min

Deciding whether to scrape

No code. For each case, argue a decision; these judgements arise in practice.

Cases

  1. A site has a paid API; the HTML is free.
  2. robots.txt disallows /search. Only /products is needed.
  3. The project needs 50,000 pages by tomorrow morning.
  4. The data is public, but it is named individuals.

No single correct answer

Each case trades the analyst’s convenience against another party’s cost or consent. A defensible argument matters more than the verdict.

Review question

A hidden endpoint with personal data

The Network tab reveals a site's hidden endpoint that returns every registered user's name and email. Is it acceptable for a project dataset?

A · Yes — it's publicly reachable
B · Yes, with time.sleep() added
C · No — personal data the site never meant to expose
D · Only on weekends

C — reachable does not mean offered.

That endpoint exposes personal data of real people, almost certainly by mistake. Harvesting it fails every Part C test; a polite request rate does not change what is being taken. The correct action is not to collect it and to consider reporting the leak.

Glossary

Week 4 terms · Part A

Asking an API

API
a web address built for programs; returns data, not pages
endpoint
one address of an API, e.g. /api/demo/sales/7
root endpoint
the API’s top address; often describes the rest
request / response
the message sent / the reply received
HTTP
the rules browsers and programs use to talk to servers
path
the address after the site name: /api/demo/sales/7
status code
three digits: 2xx success, 4xx client error, 5xx server error
body
the data part of a response (HTML or JSON)
timeout
how long to wait before giving up on a request
sandbox
a safe practice copy where mistakes cost nothing

Reading JSON

JSON
text shaped like Python lists and dicts
object / array
{ } named values (dict) / [ ] values in order (list)
key / value
the name before the colon / the data after it
null
JSON’s “nothing here”; becomes None
nested
a container inside a container: p["address"]["city"]
list comprehension
a one-line loop that builds a list: [… for p in people]
DataFrame
pandas’ table: each record a row, each key a column
boolean filter
df[test] keeps the rows where the test is True
missing value
nothing recorded; can hide behind a 0
Glossary

Week 4 terms · Parts A–C

Asking well

query parameter
a setting after ?: ?barangay=Lahug
pagination
results in pages; loop until next is None
header
a labelled note sent with a request or response
API key
a password-like code saying who is asking
rate limit
most requests allowed per minute; over it → 429
400 / 401 / 403
bad request / missing key / forbidden
404 / 429 / 500
not found / too many requests / server broke
environment variable
a setting kept outside the code, e.g. Colab Secrets

Pages and manners

dynamic page
data filled in after loading; fetched HTML is nearly empty
JavaScript rendering
the browser running page code to fetch and draw data
DevTools / Network tab
the browser’s inspection panel / its list of requests
browser automation
a program driving a real browser (Selenium, Playwright)
robots.txt
a site’s posted list of where programs may not go
terms of service
the site’s written rules of use
polite scraping
a delay between requests plus an honest User-Agent
User-Agent
the header naming the program: its name tag
personal data
anything identifying a real person; protected by law
This week's lab

Retrieving data from a real API

The lab practises on captured API replies, then calls this portal’s own live API: check the status, turn JSON into a DataFrame, filter, and pace a polite loop. ~45 minutes, in the portal’s lab page: fill each ____, press Run, then Check.

Lab tasks

requests.get with timeout, r.status_code, r.json(), params=, and pd.DataFrame(records).

Optional extension

Extract each user's city from nested JSON, and handle a request for a record that does not exist.

Summary

Four main points

Readings

Readings for next week

Next week

Data preprocessing I

Cleaning, missing data and outliers: with the raw data collected, the work of making it trustworthy begins.

DS 227 · Knowledge Discovery in Data