Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 15/ 160
01. Python & Data Wrangling

Web Scraping & API Data Extraction

Pull data via REST APIs and polite scraping with requests, pagination, and rate limits.

IntermediateREST APIs · Pagination3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

You ask a website's data service for information in small batches, politely and one at a time, then put the answers into a table.

Think of it like…

Ordering from a busy library desk: you ask for a few books at a time, follow the librarian's rules about how often you may ask, come back for the next batch (pagination), and write down what you've already collected so you don't request it twice.

Where you’ve seen it

A price tracker pulls product data from a retailer's JSON API: GET /v2/products?category=phones&page=N&per_page=100. The loop follows next_page until empty, sleeps 0.5 seconds between calls, retries 5xx errors with exponential backoff, saves each raw page to disk, and stops when the daily quota header X-RateLimit-Remaining reaches zero. The raw pages are normalised into a DataFrame and written to Parquet with a fetched_at timestamp.

Words you’ll hear

REST API
A web service returning structured data (usually JSON) from URLs, using HTTP verbs and status codes.
Pagination
Splitting results across pages via page numbers, offsets or cursors.
Rate limit
A cap on requests per time period; exceeding it returns 429 or blocks you.
Exponential backoff
Waiting progressively longer between retries (1s, 2s, 4s…), usually with jitter.

Visual diagram

Loading interactive diagram

Theory & deep dive

Calling APIs well

Use a requests.Session() for connection reuse and shared headers, always pass timeout=, call response.raise_for_status(), and parse response.json(). Authentication is usually an API key or bearer token in a header ({"Authorization": f"Bearer {token}"}), loaded from an environment variable, never hard-coded. Read the docs for pagination style: page numbers, offset/limit, or cursors (next_cursor returned each time), and loop until there is no next page.

Respect rate limits: read headers such as Retry-After or X-RateLimit-Remaining, sleep between calls, and on 429 or 5xx retry with exponential backoff and jitter (libraries such as tenacity or urllib3.Retry help). Make runs resumable by saving each raw response (or a checkpoint of the last cursor) and by being idempotent, so a crash at page 800 doesn't mean starting over. Flatten results with pd.json_normalize(items).

A cursor-paginated fetch

cursor = None; while True: r = s.get(url, params={"limit": 100, "cursor": cursor}, timeout=30); r.raise_for_status(); body = r.json(); rows += body["items"]; cursor = body.get("next_cursor"); if not cursor: break; time.sleep(0.5).

Key takeaway: Session, timeout, auth from env, pagination, backoff, and saved raw data.

Scraping responsibly

When no API exists, fetch the HTML and parse it: soup = BeautifulSoup(html, "lxml"), then CSS selectors (soup.select("div.product span.price")) to extract fields, or pd.read_html(url) for simple tables. Pages built by JavaScript don't contain the data in the initial HTML; look in the browser's network tab for the underlying JSON call, or use a headless browser (Playwright) as a last resort. Selectors break when sites change, so write defensive code, log misses and keep raw HTML for debugging.

Scraping has rules. Check the site's terms of service and robots.txt (urllib.robotparser), identify your client honestly with a User-Agent, throttle requests, don't bypass logins, paywalls or bot protection, and avoid collecting personal data unless you have a lawful basis. Prefer official APIs or licensed datasets, cache pages locally, and make conditional requests (If-Modified-Since) where supported. Unpermitted scraping can lead to blocks or legal risk, even when it's technically easy.

Extract a table, then check the rules

tables = pd.read_html(url) returns the page's HTML tables as DataFrames. Before running it in a loop over many pages, check robots.txt, add a delay and store each page to disk so you fetch it only once.

Key takeaway: Parse with selectors, prefer the hidden JSON API, and follow terms, robots.txt and privacy law.

How it works, step by step

Step 1 of 4
Research

1. Find the official route

Look for a documented API or dataset, read terms, rate limits, authentication and pagination rules.

docs · ToS · robots.txt
Key numbers at this step
Prefer
API over scraping

When to use it & trade-offs

What it is

Data you don't already have often sits behind a REST API or on a web page. With APIs you send HTTP requests (requests.get(url, params=..., headers=...)), receive JSON, handle pagination, authentication and rate limits, and flatten the result into a DataFrame. Scraping parses HTML (BeautifulSoup, lxml) when no API exists. The professional rules are the same for both: prefer an official API, respect terms of service and robots.txt, throttle requests, handle failures with retries, and cache what you fetch.

Why it matters: Pipelines for pricing, news, reviews and market data live on collecting external data reliably. Naive scripts break in predictable ways: they stop at page one, get blocked after too many requests, crash on a single timeout, or re-download everything each run. Doing this politely and robustly is a practical skill, and there are legal and ethical limits worth knowing.

When to reach for it

  • Collecting prices, reviews or metrics through documented APIs
  • Scheduled incremental data pulls
  • Parsing simple public tables when permitted

When to avoid or be careful

  • Requests without timeouts or throttling
  • Hard-coding API keys in notebooks
  • Scraping pages that forbid it or contain personal data

Ways to get external data

Official API
Best for: Most programmatic data collection

Strengths: Structured, stable, documented limits.

Watch out: Quotas, keys and sometimes cost.

Downloadable dataset / bulk export
Best for: Large, static or periodic data

Strengths: Simple; no rate limits.

Watch out: Updated infrequently; format varies.

HTML scraping
Best for: Public pages with no API, where permitted

Strengths: Works when nothing else exists.

Watch out: Fragile selectors; legal and ethical limits; JavaScript pages.

Interview signals & numbers to know

When this topic comes up

  • “How would you collect this data automatically?”
  • “The script gets blocked after a while”
  • “Handle pagination and rate limits”
  • robots.txt and terms of service
  • Incremental ingestion

Benchmarks & rules of thumb

429 -
HTTP status for "too many requests"
1s, 2s, 4s… -
exponential backoff schedule
30 s -
a typical request timeout

Common mistakes & follow-ups

Common interview mistakes

  • Omitting timeout= so one stalled connection freezes the whole job.
  • Stopping after the first page because the next-page logic wasn't implemented.
  • Committing an API token to a public repo inside a notebook.

Likely interviewer follow-ups

  • How do you handle rate limits and retries?
  • How would you scrape a site that loads data with JavaScript?
  • What legal and ethical checks do you do before scraping?
Interview tip: Start your answer with "first check for an API and read the terms". Then describe throttling, retries and saving raw data. That sequence reads as responsible engineering.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Web Scraping & API Data Extraction with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Working with CSV, JSON, Parquet & Excel
Next topic
Regex for Text Cleaning