Skip to content

Web Scraping Using API: A Step-by-Step Guide for 2026

Learn web scraping using API requests, when to switch to a browser, and how to handle blocks, retries and dynamic pages in 2026.

Pim

Pim · Founder, Scrappey

16 min read

On this page (6)

Your extraction job finished on schedule, your monitoring dashboard shows green HTTP 200 responses across the board, and the warehouse table has thousands of fresh rows. Twenty minutes later, a pricing analyst pings you on Slack because a third of the product prices are blank and half the regional variants never showed up.

That mismatch happens constantly in web scraping using API pipelines when teams measure transport success instead of data completeness. Calling an API endpoint shifts browser orchestration, proxy rotation, and request retries off your servers, which explains why adoption has accelerated so quickly. According to a 2026 Cambridge academic history of web scraping, 34.8% of surveyed developers favor web-scraping APIs specifically to overcome rate limiting, JavaScript rendering, and fragile HTML parsing. Usage volume reflects that shift too: Apify's 2025 API-growth report recorded 6.8 billion API calls in October 2024, up from 3.6 billion in January 2023.

Getting an HTTP 200 back from an API is only the starting line. A reliable pipeline checks access rules before firing the first call, matches the cheapest fetch mode to each target page, and treats every empty field or unexpected status code as a measurable data-quality defect.

Pick the Right Request Method for Each Page

Suppose you need current prices and stock flags from an e-commerce product catalog. Before writing a parser or spinning up headless browsers, ask one question: does the data you need already sit inside the server's very first response?

Answering that question in a strict order keeps your request costs low and your latency predictable. Start by checking the browser's network tab for a documented public JSON endpoint. Direct JSON calls return structured schemas with the lowest cost per request and zero DOM parsing overhead.

If no public endpoint exists, inspect the raw HTML of the page. When product names, SKUs, and prices appear in the raw source, a direct HTTP request is all you need. Only escalate to a real browser when the initial HTML is an empty shell and client-side JavaScript populates the fields after load.

When records only appear after clicking a filter, scrolling down an infinite list, or stepping through client-side pagination, you need a browser with page actions. Browser-rendered calls take longer and consume more compute than plain HTTP, so I always start with the cheapest viable method and move up only when raw responses fail to carry the fields.

How to Test Any Target Page in Two Minutes

Open a target URL in Chrome or Firefox, right-click the page, and choose View Page Source. Search the raw HTML for a specific product price you see on screen. Next, open DevTools, disable JavaScript, and reload the page. If the price disappears without JavaScript, plain HTTP won't capture it and you'll need browser rendering.

Before sending automated requests to any domain, fetch its robots.txt file and parse the rules. Under RFC 9309 from the IETF, crawlers must follow parseable robots.txt directives when the file is retrieved successfully, and parsers must support a minimum file size limit of 500 KiB. Applying per-host concurrency limits at this stage also keeps your traffic polite while you test.

Target page Method to use Why it fits Signal you chose wrong
Documented public JSON endpoint Direct API request Structured response with predictable fields, lowest cost per call Schema changes after provider or site updates
Static HTML page Direct HTTP request Full content arrives in the first response Fields empty in source, so content loads later
Client-rendered page (React, Vue, Angular) Browser render Data is built by JavaScript after load Blank container or missing elements in plain HTTP
Content behind click, scroll or pagination Browser with page actions Needs user-like interaction to reveal records Item count changes between identical runs
Login-gated content Out of scope Requires credentials the scraper should not use Redirect to a sign-in page

Because Scrappey provides a web scraping API where users send requests to extract publicly available data from websites, choosing the right mode per URL directly shapes how cleanly your requests scale. If you're mapping multiple endpoints into a single pipeline, reviewing established API integration patterns helps keep direct HTTP and browser-rendered routes cleanly separated in code.

Take two or three URLs from your own backlog and classify them against the table right now. Mark every page that redirects to a sign-in screen as out of scope before you write a single line of request code.

Confirm Access Rules Before Any Request

An HTTP 200 response tells you a page loaded. It says nothing about whether you were allowed to collect it. Engineering teams regularly treat a scraping API as a permission layer, and that is where compliant pipelines break down: an API handles network transport, header formatting, and browser rendering, but legal and policy authorization sits entirely with you.

Scrappey provides a technical service only and does not grant users permission to scrape any particular website. Only publicly available, pre-login content may be scraped; anything behind login credentials or post-login protected areas is prohibited, and every user must comply with applicable laws and each website's terms of service.

Why Checking robots.txt Alone Is Not Enough

The Robots Exclusion Protocol dates back to 1994, when Martijn Koster introduced robots.txt so site operators could declare crawler boundaries, and the IETF formally published RFC 9309 in September 2022 to standardize it. That specification explicitly notes that robots.txt is an operational crawler signal rather than an authorization system or security barrier.

Compliance with that signal is weaker in practice than most developers assume. A large-scale study of 130 self-declared bots, combined with anonymous traffic tracked over 40 days, found that bots were less likely to comply as robots.txt directives grew stricter, and AI search crawlers rarely checked the file at all. Publishers have responded by tightening restrictions: a 2026 ACM study found that 60.0% of reputable websites disallowed at least one AI crawler in robots.txt by May 2025, up from 23% in September 2023, compared with just 9.1% of misinformation websites.

Read those two findings together and the data-quality problem becomes visible. If your pipeline collects whichever sites remain technically reachable, your dataset drifts toward lower-quality sources, and you have no audit trail showing how access rules were evaluated in the first place.

Build a Four-Part Decision Layer

Treat every new target as a governance decision rather than a binary green light. When a job involves third-party APIs or publisher platforms, review the service terms alongside the target site's technical policies so you know exactly what automated collection is permitted before the first request goes out.

  • Log policy metadata early. Save a dated snapshot of the target's robots.txt file, note the relevant terms of service clauses, and record your stated crawl purpose before the first fetch.
  • Separate access from permission. A page that returns HTTP 200 in your browser is not automatically approved for automated collection, so document why your specific use case is permitted.
  • Escalate high-risk domains. Route sites with explicit AI crawler restrictions, sensitive personal data, or ambiguous terms to legal or human review rather than bypassing refusals.
  • Maintain audit logs and deny lists. Store request provenance alongside extracted data, enforce source-specific rate limits, and keep a shared deny list so excluded domains cannot slip back into future jobs.

The deny list point deserves emphasis. Access rules change over time, and a domain cleared six months ago can tighten its robots.txt or terms without any notification reaching your team. Re-running the four-part check on a fixed cadence, quarterly at minimum for active jobs, keeps your records honest.

Governance check: If you cannot explain in one plain sentence why your pipeline is permitted to collect data from a source, leave that source out of your job.

How to Send Your First API Scraping Request

A single misconfigured loop can burn hundreds of API calls before you notice the output is empty. That is why the first request goes out alone: one URL, one call, one record you can inspect by hand. Once a target page passes your access check and has a clear classification, this end-to-end test verifies authentication, rendering mode, and response structure without risking request quota.

Scrappey exposes a RESTful API with detailed documentation, and each API call counts as one request. That billing model makes the single-URL test cheap insurance against a payload error repeating across a batch.

A five-step instructional diagram explaining the process of making a first API scraping request.

  1. Generate and isolate your API key. Create a key inside your provider dashboard and store it in an environment variable such as SCRAPING_API_KEY rather than hardcoding it into source files. Credentials in the environment stay out of version control, and forgetting to load the variable is the fastest way to hit an authentication error on your very first call.
  2. Select one already-classified target URL. Pick a single public page you tested during classification, either static HTML or client-rendered. One URL makes debugging deterministic. Feed in fifty upfront and you cannot tell whether a failure came from your request payload or from one broken page.
  3. Set the request mode to match your classification. Choose direct HTTP mode for static pages and browser mode for JavaScript-rendered targets. The mode controls both speed and cost per request. Pick direct mode on a React or Vue page and you get back a clean 200 status with empty field containers, which is exactly the kind of false success that corrupts a dataset.
  4. Send a POST request with a minimal JSON body. Call the REST endpoint using cURL, Python requests, or Node fetch, passing a compact payload with only url, mode (set to direct or browser), and a headers object limited to what the target expects. Bloated or conflicting custom headers often cause targets to reject the request before rendering even begins.
  5. Inspect the HTTP status and raw body before parsing. Read the outer API status code, check the target site's returned status code, and confirm that a required marker such as a product title or price element is present in the body. Jumping straight into BeautifulSoup, Cheerio, or JSON parsing without this check turns silent HTML changes into null rows downstream.
  6. Extract structured fields and archive the raw payload. Pull your target fields into a clean record alongside source_url, status_code, and a UTC fetched_at timestamp, and write the raw HTML or JSON response to object storage. Skipping the timestamp makes change tracking impossible later, and discarding the raw body removes the only evidence available when a parser breaks next week.

Structuring the Payload and Reading the Result

Keep the JSON body lean on every call: a url string pointing to your single test page, a mode string set to direct or browser, and a headers object carrying only required fields like Accept-Language. Clean, predictable payloads make downstream integration far easier, whether the output feeds a price database or supports use cases like routing social signals into care workflows, where structured event fields trigger automated responses. Fields you did not ask for are fields you have to validate, so resist adding optional parameters until the minimal version works.

Treat the response as a data-quality measurement, not a pass or fail. A 200 from the API layer only proves the provider accepted your call. The target site's embedded status, the presence of your marker element, and the completeness of the extracted record are the three signals that tell you whether the data is usable.

A successful first API test produces exactly one complete record with every required field populated, valid metadata attached, and the unmodified raw response saved right beside it.

Don't add concurrency or loops until that single record passes manual inspection. If any required field is null, stop and inspect the saved raw body before touching a second URL.

Get Content from Dynamic Pages and Interactions

A product category page returns HTTP 200, your parser executes cleanly, and your script writes 24 products to the database. Then you open the same page in a desktop browser, scroll twice, and see 72 products.

Dynamic storefronts rarely load an entire catalog on initial paint. They defer cards through lazy loading, fetch secondary pricing blocks via XHR after hydration, or lock listings behind "Load more" buttons and location pickers. The visual below captures why a quick fixed delay misses content that streams in unevenly on modern apps.

A robot considering a 3-second loading time on a mobile shopping app with lazy loading items.

Hardcoding a fixed three-second sleep is one of the most brittle habits in browser automation. On a fast CDN hit, your job sits idle wasting compute time; during peak retail traffic, the page takes five seconds to finish rendering and your scraper captures half-empty placeholders.

Replace Fixed Sleeps with Semantic Readiness Conditions

Instead of guessing wait durations, configure your browser request to wait on a semantic readiness condition. Target a concrete signal that proves the data arrived: the appearance of a specific price CSS selector, a non-empty product grid container, or completed network idle after background API calls settle.

Once the initial render settles, match your page actions to the exact UI mechanism hiding the remaining items:

  • Trigger "Load more" controls: Send an explicit click action on the pagination button, wait for the new batch selector to attach, and repeat until the button disappears or stops returning new DOM nodes.
  • Drive infinite scroll safely: Scroll down in measured increments and check the rendered item count after each step, stopping only when two consecutive scrolls produce zero new items.
  • Walk multi-page listings with clear exit rules: Follow "Next" links or incremented page parameters using a strict stop condition, such as an empty results container, a disabled next button, or a repeated first-item ID.
  • Preserve browser sessions for stateful flows: When a site requires selecting a ZIP code, currency toggle, or category filter before displaying inventory, keep those steps inside one persistent browser session so cookies and local storage carry across actions.

Reading Hidden Application State with Custom JavaScript

Sometimes the cleanest data isn't in visible DOM text at all. Modern frameworks frequently embed full product objects inside inline script tags, window.__NEXT_DATA__, or client-side Redux stores. Running a short custom JavaScript snippet inside the rendered browser session lets you pull those structured objects directly without fighting fragile CSS classes.

Scrappey doesn't build custom end-to-end scraping scripts for users, though our team will write code snippets for AI-powered data extraction and JavaScript scenarios. Even when you start from a provider-written snippet, treat it like any other production dependency and verify its output against the live rendered page.

For a practical walkthrough of how managed browser rendering and interactive extraction behave on live JavaScript-heavy sites, watch this overview before wiring up complex action chains.

Watch the video on YouTube

Before increasing concurrency on any dynamic target, run one manual audit: count the visible items on the live page and compare that figure to the row count in your extracted output. If the numbers diverge, fix your wait condition or action sequence first.

Common API Errors and How to Fix Them

Many scraping pipelines fail without warning because their error handler treats every non-200 status code the same way: sleep a second and retry five times. That blanket retry loop wastes request credits, hammers targets that already told you to stop, and masks the underlying cause of data loss.

Start by separating HTTP 429 from HTTP 403. A 429 Too Many Requests response is an explicit volume signal telling you that your request rate exceeded what the host accepts. Lower per-host concurrency immediately and retry only with exponential backoff and jitter so parallel workers don't collide in synchronized bursts.

A 403 Forbidden response means access was refused for a reason other than pure request rate, such as client fingerprinting, missing headers, or a site policy block. Retrying a 403 in a tight loop won't solve it and will only amplify failures. Instead, inspect the response headers and access rules first; our breakdown on diagnosing HTTP 403 forbidden access denied errors walks through separating policy refusals from technical misconfigurations.

Server-side errors (502, 503, 504) and timeouts are generally transient gateway or upstream hiccups. Retry those with exponential backoff, jitter, and a hard cap on total attempts so one stalled domain can't hang your entire worker queue. A 404 Not Found means the URL moved or was removed, so stop retrying, check for redirects, and prune dead links from your seed list.

Symptom Likely cause Fix
429 Too Many Requests Request volume above what the target allows Lower concurrency for that host and retry with exponential backoff and jitter
502, 503 or 504 Transient server or gateway failure Retry with backoff and stop after a fixed attempt limit
403 Forbidden Access refused for this client, not a volume signal Check access rules and permissions; do not retry in a loop
404 Not Found URL moved or removed Update the source list and check redirects
200 OK with empty fields Content loads after JavaScript or the layout changed Switch to browser mode and wait for the required element
Results differ between runs Localization, personalization or lazy loading Fix language and geography settings, then compare repeated samples

Debugging Silent 200 OK Failures and Drifting Runs

The two trickiest bugs in web scraping using API jobs never trigger an HTTP error alert at all. The first is 200 OK with empty fields, which happens when a target shifts to client-side rendering, serves a lightweight interstitial page, or updates a CSS class name overnight.

Silent empty fields are especially destructive in commerce pipelines where teams rely on APIs for keeping catalogs in sync across channels, because a blank price or missing inventory count can overwrite valid records downstream. Catch this by checking required field presence before writing to production tables, then switching to browser mode or updating your selector path when the raw snapshot confirms a markup change.

The second tough failure is non-deterministic output: you scrape the same URL twice and get different prices, currencies, or item orders. Localization, geo-IP routing, A/B testing, and lazy loading cause most of that drift. Lock your target country, Accept-Language header, and session settings across runs before comparing outputs.

Log every response's status code alongside its URL, host, latency, and extraction completeness. Reviewing error distribution by domain over time shows you immediately whether a pipeline is hitting rate ceilings, dead URLs, or parser rot.

Validate Coverage and Pilot Before Scaling

A scrape that returns HTTP 200 on every URL can still leave you with an unusable dataset missing major chunks of its catalog. Reliability in web data collection has to be measured as field-level coverage and entity completeness, not raw page retrieval.

Evidence from an academic web-scraping reliability benchmark shows how drastically small configuration shifts alter what you collect. Changing the browser profile alone produced only 70.3% overlap with a reference collection, while one traversal strategy missed 77.4% of relevant population units and a keyword-marker strategy missed 46.0%.

Change tested Result
Browser profile only 70.3% overlap with reference collection
Traversal strategy 77.4% of relevant population units missed
Keyword-marker strategy 46.0% of relevant units missed

Those gaps happen without throwing a single exception in your logs. If you don't measure coverage deliberately before scaling up, you'll only discover the missing data when someone downstream questions the numbers.

A checklist infographic outlining steps to validate data coverage and run a pilot before scaling web scraping.

Build a Quarantine Gate and Validation Rules

Start by writing down your expected entity population and the required fields for each record (for example, SKU, product title, currency, and numeric price). Next, collect repeated samples of the same URLs under identical browser, language, geography, and session settings, then compute both URL-level and field-level overlap between runs.

Run every extracted record through schema checks before it enters your main database. Enforce strict data types, sensible numeric ranges, and cross-field rules, such as confirming that a sale price never exceeds the list price. Applying structured data validation methods at ingestion converts vague "it looks right" spot checks into automated quality gates.

When a record misses a required field, fails schema validation, or shows an unexpected page fingerprint shift, quarantine it instead of dropping it or writing nulls. Retain the raw HTML or rendered snapshot for every quarantined case so an engineer can tell in seconds whether the upstream site changed its layout or the product lacked a discount price.

Track five domain-level health metrics continuously:

  • Field-Level Coverage: Percentage of fetched records containing valid, non-null values for every required field.
  • Duplicate Rate: Share of repeated entity IDs or URLs indicating broken pagination or unstable sorting.
  • Latency Percentiles: Track p50, p95, and p99 response times to spot slowing hosts early.
  • Retry Amplification: Ratio of total API calls sent to unique target URLs completed, which flags silent cost spikes.
  • Error Breakdown: Count of 429, 5xx, 403, and 404 responses per host so you can lower concurrency when latency, 5xx errors, or 429s climb.

Run a Controlled Pilot Before Going Full Scale

Before scheduling thousands of URLs, run a tightly scoped pilot. As a practical example, test a batch of 50 to 100 URLs that intentionally mixes at least one static HTML page, one client-rendered page, and one page requiring click or scroll actions, logging every status code and field coverage rate.

Keep direct HTTP requests wherever field coverage holds steady, and promote a target to browser mode only when direct calls miss required elements. Lock in conservative per-host concurrency limits during the pilot rather than after you trigger rate limits. Scrappey offers 150 free scrapes to start, which gives you enough headroom to run that initial validation pilot, and once your checks pass, it plugs cleanly into n8n, RapidAPI, Apify, an MCP Server, or the CLI for scheduled production jobs.

Don't scale a scraping job until required-field coverage stays consistent across repeated pilot runs and every observed error code has a documented, tested fix.


If you want to put this workflow into practice without maintaining browser clusters or proxy pools yourself, Scrappey gives you a single RESTful API with both direct HTTP and full-browser modes for publicly available web data. You can start with 150 free scrapes to classify your target pages, validate field-level coverage on a pilot batch, and connect clean outputs directly into your existing data or automation stack.

#web scraping API#API scraping#dynamic pages#scraping API tutorial#JavaScript scraping

Collect web data without running the infrastructure

Scrappey handles browsers, proxies and retries behind one API. Free credits to start, no card needed.