You've got a target list, a deadline, and three tabs open, one for an official API, one for a page that only shows the field you need after JavaScript runs, and one for a scraping provider charging per call. Your first Python script returns HTTP 200, an empty list, and no usable records. That's the normal starting point, not a sign you've picked the wrong language.
The fix isn't a bigger scraper. It's a routing decision you can measure, a parser that rejects bad records early, and a retry loop that counts usable records instead of successful calls.
Table of Contents
- Pick the Right Data Source Before You Write Code
- How to Authenticate and Make Your First Request
- Parse Paginated JSON Into Clean Records
- Stay Under Rate Limits and Catch Errors HTTP 200 Hides
- Check Compliance Before an Agent Runs Your Scraper
- Connect the Client to Your Agent and Run It
Pick the Right Data Source Before You Write Code
Start with the field you must have, not the library you like. Web scraping using API in Python gives you three routes, and each fails differently. An official API returns typed, documented data. Direct HTML extraction with Requests and Beautiful Soup returns whatever's visible on the page. A third-party scraping API renders the page for you and charges per call.
The comparison in the AlterLab guide to web scraping versus official APIs captures the tension well. Official APIs provide typed, structured data and documented limits, while scraping can expose visible fields that APIs omit but introduces undocumented blocking, CAPTCHA, and layout-change risk. Neither route wins in the abstract.
Choosing a Data Source by Job Requirement
| Source | Field completeness | JavaScript pages | Volume and freshness | Failure cost |
|---|---|---|---|---|
| Official API | Typed and documented, but some visible fields missing | No rendering needed | Documented quota, fresh per call | Quota exhaustion, clear error contract |
| Direct HTML extraction with Requests and Beautiful Soup | Every visible field, but tied to page layout | Usually needs a headless browser | Limited by blocks and CAPTCHAs | Silent breakage on layout change |
| Third-party scraping API | Fields as the provider defines them | Handled by the provider | Pay per call, provider-side limits | Per-call cost, plus wasted spend on failed calls |
Say you're building a lead list. The official endpoint returns company name, domain, and headcount, but no contact email. The email sits on the company's public team page. I would call the API first, validate what's missing, and only escalate the incomplete records to rendered extraction.
That escalation path is the point. You're not choosing API versus scraping once for the whole project. You're routing per record based on field completeness and observed errors.
- Field completeness: Will the source return every required field, or will you discover gaps after paying?
- JavaScript requirements: Does the data exist in the initial HTML, or does it appear only after rendering?
- Volume and freshness: Can you get enough current records inside the documented quota?
- Failure cost: Does failure mean a clear error, a wasted paid call, or an incorrectly generated spreadsheet?
Housing research shows why visible fields matter. If you're comparing rental markets, the listings behind studio and two-bedroom rent comparisons include layout and location context an API summary might flatten or omit. Your source choice depends on whether those fields drive the decision.
A gateway such as looot can route a job to a provider, but the routing decision stays with you. Record which route produced each record, so you can explain gaps later.
If a required field is missing in more than one response in ten, the next route is worth its cost.
How to Authenticate and Make Your First Request
Build one small request that works before you build pagination, retries, or an agent tool around it. The listing below assumes a provider that accepts a bearer token and query parameters. Adapt the endpoint and parameter names to your provider's contract.

import os
from urllib.parse import urljoin
import requests
API_KEY = os.environ["SCRAPING_API_KEY"]
BASE_URL = "https://api.example-provider.com/"
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {API_KEY}",
"Accept": "application/json",
})
url = urljoin(BASE_URL, "v1/companies")
response = session.get(
url,
params={"query": "logistics software", "limit": 5},
timeout=(5, 20),
)
response.raise_for_status()
payload = response.json()
print(payload["data"]["results"][0])
Why Each Step Is There
1. Install requests in a virtual environment. Run python -m venv .venv, activate it, then pip install requests. An isolated environment keeps your scraper from inheriting a broken system package or a colleague's unrelated upgrade.
2. Store the API key in an environment variable. Read it with os.environ, never paste it into source code. A hardcoded key ends up in version control, screenshots, and shared notebooks. If the variable's missing, failing immediately is better than sending an unauthenticated request and debugging a vague provider error.
3. Build the URL and pass parameters separately. Use urljoin from urllib.parse for the endpoint and pass params as a dictionary. Concatenated strings break on spaces, ampersands, and values you didn't write yourself. Requests encodes the dictionary for you.
The standard library already covers much of this ground. The Python documentation for urllib describes urllib.request as supporting authentication, redirects, cookies, and proxy handling, with urllib.parse for constructing URLs and urllib.robotparser for robots.txt. Requests is a convenience layer, not magic.
4. Create one session and set an explicit timeout. A requests.Session reuses connections and keeps your headers in one place. timeout=(5, 20) means five seconds to connect and twenty seconds to read. Without it, a stalled provider can occupy a worker indefinitely.
5. Call raise_for_status() before reading the body. Don't parse JSON from a failed response and hope it resembles data. Let HTTP errors raise, then handle them deliberately in your retry logic.
6. Print one record, not the whole payload. Confirm the key names, nesting, and value types against the provider dashboard. A wine data integration makes the pattern concrete, you can integrate with the Wine Labs API using the same session, header, and timeout structure, swapping only the endpoint and fields.
Success check: You should see an HTTP 200, a JSON body with the expected keys, and a record count that matches the limit you sent. Anything less is a request that arrived, not data you can use.
Parse Paginated JSON Into Clean Records
Don't assume the top level of the JSON is your list. Providers commonly nest results under data.results, items, or a named collection, with pagination metadata beside it. Print the top-level keys once, locate the list, then write the parser against that actual shape.
Follow the Cursor, With a Stop
Read the next-page cursor or next URL from each response and loop until it's empty. Add a maximum page count anyway. A provider bug that returns the same cursor twice shouldn't become an infinite paid loop.
Store the cursor after each successful page. If page nine fails, you resume from page nine instead of buying pages one through eight again.
Map Everything to One Internal Schema
Different providers name the same thing differently. One returns employee_count, another returns staff_size, a page scrape returns text scraped from a heading. Map all of them onto one internal schema at the parsing boundary.
- Trim whitespace: Strip names, titles, and domains before comparison or deduplication.
- Lowercase domains: Treat
Example.COMandexample.comas the same company. - Convert dates to ISO 8601: Store one sortable format instead of provider-specific strings.
- Keep currency in one unit: Record the currency code beside the amount, and don't mix cents with whole units.
- Preserve missing values: Store
Nonewhen a field's absent, never invent a plausible default.
That last rule matters more than it sounds. Say a company record has no employee count. If you store zero, later analysis treats a missing answer as a tiny company. Flag it as missing so the gap stays visible.
I would define the schema as a dataclass or a pydantic model. A malformed field then fails during parsing, where you still have the provider response in hand, instead of three stages later in a spreadsheet.
Keep Provenance Beside Every Record
Save the provider name, endpoint, request timestamp, parser version, and raw response beside the cleaned record. Validate required fields at the same point and count rejected records separately from accepted ones.
This isn't archival fussiness. When a field looks wrong next week, the raw bytes let you replay the parser and work out whether the provider changed, your mapping broke, or the source data was wrong all along. Without them, you're rebuying the call to investigate a record you already paid for.
Stay Under Rate Limits and Catch Errors HTTP 200 Hides
Rate limiting is a protocol requirement, not a performance tune-up you add after launch. Get this wrong and you'll turn a brief provider slowdown into a self-inflicted outage, duplicate records, and a bill for calls that returned nothing usable.

As MDN's reference for HTTP 429 explains, HTTP 429 means the client exceeded a server-defined request rate, and the server may include Retry-After. That value may be either a delay in seconds or an HTTP date, so your code has to parse both forms before sleeping. Guessing a fixed delay ignores the one useful instruction the server sent you.
Run the Retry Sequence in Order
1. Read quota headers on every response. Record remaining calls, reset time, and the provider request ID. Don't wait for a 429 to learn you're nearly out of quota.
2. Keep one limiter per API key and endpoint. A token bucket works well because it smooths bursts without forcing a rigid sleep after every call. Separate limiters stop a cheap endpoint and an expensive endpoint from competing for the same budget.
3. Cap concurrency at a few workers. Parallelism multiplies both throughput and mistakes. Start low, watch the 429 rate, and raise the cap only when the provider stays quiet.
4. Honor Retry-After exactly when it's present. If the header's absent, use exponential backoff with randomized jitter. Jitter matters because workers that failed together will otherwise retry together.
5. Stop after a small retry budget and surface the failure. A call that fails after its budget belongs in a failure log with its status, latency, and retry count. It doesn't belong in your success metrics.
The arithmetic is unforgiving. If 100 workers each retry three times immediately, one logical request can become 400 requests. You've deepened the throttle, and if the provider bills attempts or returns partial duplicates, you've also created duplicate billing or duplicate records.
Retry selectively. Transient connection failures, timeouts, 429 responses, and usually 5xx responses deserve another attempt inside the budget. Authentication failures and malformed requests don't. Retrying a bad key just produces the same rejection more slowly.
Separate a rate limit from a quota. A 429 may clear after waiting. An exhausted daily or monthly quota won't, so sleeping and retrying burns time without changing the answer. Treat quota exhaustion as a stop condition for the run, then report how many records you secured.
Make writes idempotent before you scale retries. Use a stable key built from provider, endpoint, canonical URL, and content hash. Then a retried request updates the same record instead of creating a second copy.
Response Types, Likely Causes and the Action to Take
| Response | Likely cause | Action |
|---|---|---|
| HTTP 429 | Rate limit exceeded | Wait for Retry-After or back off with jitter, as covered earlier |
| Read timeout | Slow provider or stalled connection | Retry once with backoff, keep explicit timeouts |
| HTTP 200 with an error object | Provider error hidden in the body | Treat as a failure and log the provider request ID |
| HTTP 200 with an empty list | Empty result or stale cache | Check the query and freshness, mark as unusable if data was expected |
| Partial pagination | Cursor stopped early | Resume from the last cursor and compare counts with the reported total |
The table's last three rows are where scrapers lose data. A successful TCP exchange doesn't mean successful extraction. APIs can return HTTP 200 with an error object, partial pagination, stale cache data, or an empty result.
Check for an error key before you read data. Compare the number of records you collected with the total the provider reported. Check freshness timestamps when the provider gives them, because a cached empty list and an empty result need different responses.
Say you request five pages of company records. Pages one to three return records, page four returns an empty list, and the cursor disappears. If the provider reported a larger total, that's partial pagination, not completion. Resume from the last good cursor and mark the run incomplete until the counts reconcile.
Measure What You'll Actually Ship
Track effective throughput as successful usable records divided by elapsed time. Record the 429 rate, timeout rate, schema-failure rate, and cost per usable record beside it. A run with fewer calls but more complete records beats a faster run full of rejects.
Count usable records, not successful calls. HTTP 200 is transport news, not data quality news.
Test these paths before production traffic finds them for you. Build a mock server that emits 429 with both Retry-After forms, malformed JSON, delayed reads, and 5xx responses. Verify that retries preserve idempotency, that failed calls surface in your logs, and that your counters never call an unusable response a success.
Check Compliance Before an Agent Runs Your Scraper
Compliance isn't a yes-or-no question you answer once in a README. It's a set of checks your code runs before each call, especially when an agent can expand its own target list.

As the guide to whether web scraping is legal notes, robots.txt is not access authorization under RFC 9309, yet ignoring it can still affect site policy, contractual disputes, and evidence of abusive behavior. Privacy is separate again. Processing personal data requires a lawful basis under GDPR, and legitimate interest requires purpose, necessity, and balancing analysis.
Put a Control Plane in Front of the Client
- Classify each field: Mark it personal or non-personal before you request it, and don't collect fields your purpose doesn't need.
- Check robots.txt and provider terms: Honor disallow directives for the target. Our terms prohibit illegal scraping, bypassing rate limits, reselling access without an agreement, and interfering with the gateway, providers, or other customers.
- Write an audit entry: Record purpose, timestamp, target, provider, and outcome for every request.
- Enforce per-site concurrency caps: Keep limits attached to the site and key, not buried in a worker setting.
- Check deletion and suppression lists: Run the check before every request, not during a monthly cleanup.
- Stop at CAPTCHA or login barriers: Treat them as signals to escalate to a human, not obstacles to work around.
The walkthrough below is useful context for how these policy choices show up in a real scraping workflow.
Say an agent expands a job from twenty approved companies to two thousand because the first results look promising. That isn't research at a larger scale, it's an uncontrolled crawl. A control plane catches the shift because volume is checked against the approved purpose before execution.
Never let an agent route around a rate limit to finish a job. If the approved route is blocked, the correct output is a bounded failure a person can review.
Connect the Client to Your Agent and Run It
Wrap one tested client function as a tool your agent can call. Don't expose raw HTTP, provider URLs, or retry settings to the model. The agent needs a narrow contract, clear costs, and a result that states what failed.

Define the tool with a name, a plain description of what it returns, and an input schema containing a query and a field list. That's the information MCP-compatible agents use to choose tools. Return the records, the usable record count, rejected records, and failures in one structured result.
With looot, your AI agent gets one API key and one prepaid balance for paid data APIs of many providers, including web search, work emails, company data, and social profiles. Scraping at scale starts from $0.0035 per call, so a few dozen test calls cost little. Check the quoted price before each call when the provider gives one.
Run the First Job Small
- Create a looot key and load a small prepaid balance.
- Run one endpoint with a five-record limit through the same session and parser you'll use in production.
- Check the ledger for the price charged and compare it with the usable records returned.
- Add the rate-limit and error handling around that proven call, then test it against your mock failures.
- Scale only once cost per usable record is known and your rejected-record count is explainable.
Assemble the session, pagination, parser, and retry loop into a single script of about sixty lines. The tool should wrap that tested function, not fragments copied between notebooks. One function also gives you one place to enforce timeouts, provenance, and compliance checks.
Keep the tool description honest. If it returns company records but email may be missing, say so. An agent that knows a field can be absent can route incomplete records for enrichment instead of presenting gaps as facts.
Tonight's test is deliberately boring. One call, one saved record, one logged failure. If all three work, you have a client worth scaling.
Create your key at looot, load a small balance, and run your first five-record scraping job through one prepaid account instead of juggling separate provider signups. You'll see the quoted price before the call and the settled cost beside the result, so you can judge the run by cost per usable record.



