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
URLs built for programs, which return clean JSON.
When the fetched HTML differs from the displayed page, and how to proceed.
robots.txt, rate limits, keys and personal data: the rules of collection.
Last week's lab parsed a page already in hand. This week the data is fetched over the network, from a server someone else operates.
A scraper is often unnecessary, because an API already exists.
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.
Fetch HTML built for reading, locate the right class, and depend on the page not changing.
Request data from a web API, a URL built for programs, and receive structured data without tags.
Check for an API before scraping a page; an API is faster, more robust, and fairer.
Roy Fielding’s PhD thesis (UC Irvine) describes the style most web APIs follow.
Kenneth Reitz releases it on 14 February: “HTTP for Humans”.
Reitz hands the project to the Python Software Foundation.
Python’s built-in urllib could already fetch pages; requests made the same job short enough to read at a glance.
An API that follows REST answers ordinary web addresses with data (often JSON) instead of a web page.
SourceWikipedia: Requests; Wikipedia: REST; requests.readthedocs.io
downloads in September 2026: about 460 every second.
More downloads that month than NumPy (793 million) or pandas (543 million).
Maintained under the Python Software Foundation, the non-profit behind Python.
Many other packages depend on requests, so installing them installs it too: it is a building block of the Python ecosystem.
SourceDownloads: pypistats.org (requests, numpy, pandas), without mirrors, retrieved 11 Oct 2026; Wikipedia: Requests
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
One specific address of an API. Each endpoint serves one kind of data.
e.g. /api/demo/sales/7 gives sale number 7
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
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
Text written like Python lists and dictionaries; the usual format of API replies.
e.g. {"item": "kape", "qty": 2}
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
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
JSON’s word for “nothing recorded here”. Python turns it into None.
e.g. "closed_on": null becomes None
A setting after ? in the address that narrows the request.
e.g. /api/demo/sales?barangay=Lahug
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": …
A labelled note that travels with a request or response, outside the data itself.
e.g. Retry-After: 60
A password-like code that tells the API who is asking; often raises the rate limit.
e.g. X-API-Key: latarak-demo
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
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
The browser running the page’s own program (JavaScript) to fetch data and draw it.
e.g. visible in Inspect, missing from View Source
A plain-text file at a site’s root listing where automated programs should not go.
e.g. Disallow: /private/
The site’s written rules of use. They can forbid scraping even of public pages.
e.g. “no automated collection” clauses
Collecting slowly and openly: a delay between requests, and a User-Agent header identifying the requester.
e.g. time.sleep(1)
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.
HTTP (week 3: the rules browsers and programs use to talk to
web servers) is identical to last week. The GET arrow is the request
(“send me this”); the arrow back is the response. What changes is its
body, the data part: JSON built for code instead of HTML built for a browser.
A web page is a restaurant’s dining room, arranged for people, while an API is the take-out window, where an order slip in the agreed format returns a packed box.
API: Application Programming Interface — a contract: "ask this URL (web address) this way, get data back this shape." Each such URL is an endpoint.
The requests library (ready-made code, week 3) handles the networking. The remaining task is last week's guideline: status first, body second.
timeout=30Network requests can stall. Without a timeout the notebook waits indefinitely; with one, an unresponsive server produces an error that can be handled.
import requestsload the requests library, which sends web requestsr = requests.get("…/users", timeout=30)send a GET request to that address and keep the whole reply in r; give up after 30 secondsr.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 dictslen(data) → 10the body was a list of 10 records: ten usersCurly braces, square brackets, key–value pairs. One
r.json() call converts the text into familiar dicts and lists.
{ }"id": 1 the key is the name "id", the value is 1[ ]"address": {"city": …}Compared with last week’s nested <li> markup, the structure here is the data.
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).
| JSON | Python | Example |
|---|---|---|
object { } | dict | u["name"] |
array [ ] | list | data[0] |
| string | str | "Cebu" |
| number | int / float | 27.5 |
true / false | True / False | "open": true |
null | None | None: a gap that must be handled |
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
BASE = "https://portal.latarak.com"a variable holding the site’s address, typed once and reused on every slideBASE + "/api/demo"+ joins two pieces of text into one full address; /api/demo is the endpointFictional sari-sari store sales, but the status codes, pagination, errors and rate limits behave as in a real API.
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.
It names every endpoint, the auth header, and the rate limit: the three items needed before writing a loop.
d["name"]look up one key of the dict and get its valuefor name in d["endpoints"]:endpoints is a dict inside the dict; looping over it gives its keys, one endpoint per linethe outputthree endpoints, an optional key sent as a header, and the rate limit: 12 requests a minute without the keyA 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).
| Code | Means | Action |
|---|---|---|
200 | OK | Parse the JSON |
400 | Bad request (a setting in the request is not allowed) | Read the error, fix the request |
401 | No / bad key | Correct the credentials |
404 | No such record | Nothing to parse — handle it |
429 | Too many requests | Slow down, wait, retry |
500 | Server broke | Server-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.
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.
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.
There are only 60 sales. A good API does not crash or return an empty 200; it returns 404 (“not found”) with an explanation.
The hint ("Valid ids are 1..60") describes the API’s valid inputs, and is frequently overlooked.
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.
200 parse · 400 correct the request · 404 record does not exist · 429 reduce the rate.
Each JSON object becomes a row; each key becomes a column. The result is an ordinary pandas DataFrame, as in earlier weeks.
The column list [["id", "name", "email"]] is a selection; adding a key to it keeps one more column.
URLthe users address from the earlier slide, kept in a variablepd.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 themdf.shape → (10, 3)the table’s size: 10 rows (users) and 3 columnsA 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.
The lab builds this name + city table using chained keys only.
personone record from the list, e.g. people[0]person["address"]its value is a whole dict, not a single piece of textperson["address"]["city"]two keys in a row: open address, then take city from inside itrows = [ {…} for p in people ]a list comprehension: a one-line loop that builds one small dict per person and collects them all in a listA 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).
Spaces, symbols and Unicode all need escaping. params= handles this correctly; manually concatenated URLs eventually fail.
params={"postId": 1}the filter as a dict: key = the parameter’s name, value = the requested valuer.url → …/comments?postId=1the full address requests actually sent: it added ?postId=1 automaticallylen(r.json()) → 5the server sent back only the comments on post 1: five of themDownloading 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.
d["total"] → 12d["pages"] → 3d["results"]Passing a dict lets requests encode spaces and symbols correctly. Building the URL by hand is a common cause of unexplained 400s.
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]:send the request three times, once per page number"page": pagethe query parameter that picks which page comes backlen(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 collectedA 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).
A 400 body that only says "Bad Request" indicates a poorly designed API. This one names the limit and the header that raises it.
A loop of API calls suddenly starts returning 429. What does the server indicate?
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.
Codes starting with 4 indicate a problem with the client’s request; 5 indicates a server problem.
Request rate is an ethical choice as well as a technical one.
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.
d["source"]["licence"]source dict, then its licenceBetterGov.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.
The discovery (root) endpoint carries a data_quality_warning. Most APIs do not, but when one does, reading it prevents publishing a false claim.
The following slides deliberately ignore this warning to show the consequence.
Every project has a contract id and represents real funds, a real contractor, and a real location.
One storm surge protection structure in Donsol, Sorsogon: the scale of a single row in this file.
…/projects/22F00136a single-item endpoint: the contract id goes in the pathfor k in ("status", …):repeat for each of the four key names in the bracketsprint(k, "=", p[k])print the key’s name, an equals sign, and that key’s value from the record34,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.
"Region III" contains a space. requests encodes it; a hand-built URL produces an unexplained 400.
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.
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.
headers=KEYsend the API key as a header, so 100 rows a page are allowedwhile True: … breakrepeat for ever, until break jumps out of the looprows += d["results"]add this page’s records to the growing listif not d["next"]: breakif there is no next page (None), stop; otherwise page += 1 requests the next55 541255 pages fetched, 5,412 projects collectedWith 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 projectdf["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 firstName: count, dtype: int64the result is named count and holds whole numbersdf[df["status"] == "Completed"]a boolean filter: keep only the rows where the test is Truecomp["amount_paid"] == 0True for each completed project whose amount_paid is 0All 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.
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.
amount_paid is not populated in this export. It says nothing about whether anyone was paid, so the ₱201B finding is unsupported.
The code was correct. The filter was correct. The sum was correct. Every number on the previous slide is true.
“Zero in a column” and “zero pesos paid” are different claims. The data cannot distinguish them; the analyst must.
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.
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.
/api/demo/barangays and count them.id=42; record its item and total.barangay=Lahug; count the rows.limit=99; record the status and the body’s message.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.
Next: pages that load their data dynamically, and the ethics of collecting it.
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.
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.
find_allThe 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.
Ctrl+U in most browsers. The raw response: exactly what requests receives. If the data is not here, plain scraping cannot retrieve it.
DevTools (the browser’s developer tools: F12, or right-click → Inspect)
show the live tree after JavaScript ran: what the browser built and displays.
The one-minute test: open View Source and search for a value visible on screen. Found: static, so last week's tools work. Missing: dynamic, so another method is needed.
A sixty-second check can save an afternoon of debugging an "empty" scraper.
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.
Each row in the Network tab is a request the page made while building itself.
Click a Fetch/XHR row and preview the response; one of them holds the data in clean form.
Copy that URL into requests.get(); the task is then the same as Part A, with no HTML.
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.
The program sees exactly what a user sees, on any page, however dynamic.
A whole browser per script: slow, memory-hungry, fragile to site redesigns.
It is a last resort. The hidden-API method usually suffices, and this week's lab needs neither.
Use it: cleanest data, clearest rules; Part A suffices.
Static page: requests + BeautifulSoup, as last week.
Call the site's own JSON endpoint directly.
Browser automation: powerful, heavy, last resort.
Each step down this list costs more code, more fragility and more server load; the first method that works is used.
The Part C questions apply: whether collection is permitted, and whether the request rate is reasonable.
| Situation | Method | Reason |
|---|---|---|
| There is a documented API | API | Clean JSON, paginated, stable. The first option to check. |
| Data is in the page source | requests + parse | Last week’s skill. Cheap, but breaks when markup changes. |
| Page is empty until JS runs | find the hidden API | Open DevTools → Network to find the page’s data request. |
| Genuinely nothing else works | drive a browser | Slow, heavy, brittle. The last resort, not the first. |
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.
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.
A 429 means the request was valid but too many were sent. Retrying immediately makes it worse.
for i in range(15):repeat the indented lines 15 timesprint(r.status_code, end=" ")print each code followed by a space instead of a new linetwelve 200s, then 429the first 12 requests this minute are served; numbers 13, 14 and 15 are refusedThe 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 60time.sleep(60)pause the program for 60 seconds, then retryif r.status_code == 429: time.sleep(int(r.headers["Retry-After"])) then retry. This is well-behaved scraper behaviour.
A request returns 429 with Retry-After: 36. What should the code do?
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.
Same request, one extra header, and the limit goes from 12/min to 200/min. A key lets a site identify the client.
headers={…}send one header with the request: its name is X-API-Key, its value is the key200the same second that gave 429 without a key now succeedsThe 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 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.
"Everyone: stay out of /private/ and /search, and pause 10
seconds between requests."
User-agent: *the rules below are for every program (* = everyone); a user agent is a program’s name tagDisallow: /private/do not fetch any address that starts with /private/Crawl-delay: 10wait 10 seconds between requestsUser-agent: Googlebot / Allow: /Google’s crawler may fetch everythingA tight loop of requests is indistinguishable from an attack. A small pause (a delay) keeps the scraper courteous and prevents bans.
429 still occursStop, wait longer, and re-read the API's documented limits. Retrying instantly makes it worse.
for i in [1, 2, 3]:fetch users 1, 2 and 3, one request eachf"…/users/{i}"an f-string: {i} is replaced by 1, then 2, then 3names.append(u["name"])add each name to a list names made before the looptime.sleep(0.3)wait 0.3 seconds before the next requestPolite 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.
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.
HEADERS = {"User-Agent": …}the identification: the program’s name plus a contact addressheaders=HEADERSsend that header with every requesttime.sleep(1)the delay: wait one second before the next requestr.request.headers[…]what was actually sent: the server received the identificationMany APIs require one to track quota and identity. Everything done with it is attributed to its owner.
An environment variable or a secrets store — in Colab, the Secrets panel ( icon), read at runtime.
Not pasted in the notebook, not committed to git (saved into a project’s version history, often published on GitHub). A pushed key remains public, because the history retains it.
The course already uses this pattern: the portal submit token is stored in Colab Secrets, not in the notebook.
Revoke and reissue it immediately; deleting the file that exposed it is not sufficient.
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.
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.
| Check | Reason |
|---|---|
| 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. |
Terms of service (the site’s written rules of use, usually linked at the
foot of every page) and robots.txt both apply. "The page loaded" is not permission.
Personal data (anything that identifies a real person: names, emails, ID numbers) carries legal weight — in the Philippines, the Data Privacy Act of 2012. Public ≠ free to harvest.
Research and journalism weigh differently from reselling a copied database. Purpose determines what is defensible.
A useful test: whether the scrape (source, volume, purpose) could be explained comfortably to the site's owner and to the people in the data.
Ethics & privacy receive a full week; this is the minimum standard until then.
No code. For each case, argue a decision; these judgements arise in practice.
/search. Only /products is needed.Each case trades the analyst’s convenience against another party’s cost or consent. A defensible argument matters more than the verdict.
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?
time.sleep() addedC — 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.
Technical access and permission are different questions; ethics applies when only the first is satisfied.
The hidden-API method applies to data the site already shows everyone, not to what it accidentally exposes.
/api/demo/sales/7/api/demo/sales/7{ } named values (dict) / [ ] values in order (list)Nonep["address"]["city"][… for p in people]df[test] keeps the rows where the test is True?: ?barangay=Lahugnext is NoneThe 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.
requests.get with timeout, r.status_code,
r.json(), params=, and pd.DataFrame(records).
Extract each user's city from nested JSON, and handle a request for a record that does not exist.
Check for one before scraping; JSON is more reliable than searching tags.
The same practice as last week; 401 and 429 concern the client.
View Source to diagnose; the Network tab usually reveals the site's own endpoint.
robots.txt, request rate, keys in secrets; personal data is not free to collect merely because it is reachable.
Summary: use the cheapest method that works, and follow the rules at every step.
With acquisition done, CRISP-DM's (week 2) Data Preparation phase begins, over the next two weeks.
Requests docs, "Quickstart": the functions from this week, on one page.
requests.readthedocs.io
MDN, "An overview of HTTP"; also read robots.txt on two frequently visited sites to see what they ask of crawlers.
Both are linked on the course page beside this deck and the lab.
After the lab, the Quickstart reads as a summary of code already run.
Cleaning, missing data and outliers: with the raw data collected, the work of making it trustworthy begins.
DS 227 · Knowledge Discovery in Data