Call a web scraping API from Python: requests, errors, retries and async jobs
Call a web scraping API from Python with requests: pin an extractor version, read the result, handle errors and retries, and poll a 202 async job.
- Published
- Reading time
- 9 min read
- By
- ExtractHub team
- Python
- web scraping API
- error handling
- async jobs
- tutorial
On this page
Most Python scrapers start as requests.get(url) plus BeautifulSoup. That is fine until you run it from a cron job and need to know why a page came back empty, whether a failed request cost money, and what to do when the remote side is busy. This guide shows how to call a web scraping API from Python instead: one HTTP call returns structured JSON, and the status codes tell your code what happened.
The examples use the ExtractHub extract API and the standard requests library. Everything below (parameters, headers, error codes, the async job path) is taken from the API’s code, and the full reference is in the API reference.
What you need before the first call
- An API key from the API keys page. A live key (
exth_live_...) fetches real pages and uses credit. A test key (exth_test_...) never fetches anything and never uses credit; it is the right key for writing and testing the client below. - A released extractor. An extractor is a versioned web scraper: the fetch options and the fields to pull out of a page. You can build one with the agent skill (see how to build a web scraper with Claude Code) or pick a public one from the extractor catalog. Its page shows the output schema, so you know the field names before you write code.
- Python 3 with
requests(pip install requests).
Keep the key out of the code:
export EXTRACTHUB_API_KEY="exth_test_..."
The first request: a pinned extractor and a target URL
The simplest call is a GET with two query parameters: target_url, the page to scrape, and extractor_id, the extractor with a version pin.
import os
import requests
API_URL = "https://api.extracthub.io"
session = requests.Session()
session.headers["X-API-Key"] = os.environ["EXTRACTHUB_API_KEY"]
resp = session.get(
f"{API_URL}/api/extractor/extract",
params={
"target_url": "https://www.example.com/p/123",
"extractor_id": "@you/example-product@1",
},
timeout=(10, 120),
)
resp.raise_for_status()
body = resp.json()
print(body["result"]["extracted"])
requests encodes the @ and / of the extractor id in the query string for you. The key can also go in Authorization: Bearer <key>; send one or the other, because two different keys in both headers are rejected with a 400 ambiguous_credentials.
The pin is not optional. @you/example-product@1 follows the latest 1.x release, @you/example-product@1.2.0 freezes one exact version, and @you/example-product@draft runs the unreleased draft (owner only). An id without a pin gets a 400 pin_required whose message lists the available majors. The versioned web scraper post explains why pins exist and when a new major is released.
The read timeout is generous on purpose. A realtime request can wait up to 30 seconds for scraping capacity before the API turns it into a job (see below), and the page fetch comes on top of that. A short timeout would cut off requests the server is still working on.
What a successful response looks like
A 200 answer wraps the result in { "success": true, "result": ... }. An illustrative example for an imaginary product page:
{
"success": true,
"result": {
"extracted": {
"title": "Example headphones",
"price": 49.9,
"inStock": true
},
"metadata": {
"useProxy": true,
"renderJs": false,
"url": "https://www.example.com/p/123",
"scrapedAt": "2026-11-22T08:00:00.000Z"
}
}
}
The useful parts for your code:
result.extractedholds the fields of the extractor’s output schema. Top-level fields markedrequiredare guaranteed to have a value, because an empty required field fails the request instead (more on that below).result.metadatasays how the page was fetched (useProxy,renderJs), when, and what the call cost (costUsd, in USD; current prices per tier are on the pricing section).escalated: trueappears when a plain fetch came back unusable and was retried with JavaScript rendering, andwarningslists non-blocking findings.- A test key adds
"sandbox": trueto the result.
Headers worth reading
The response headers carry information you should log, not ignore:
| Header | Meaning |
|---|---|
X-Extractor-Version | The exact version that ran, for example 1.2.0 (or draft). |
Deprecation, Sunset | The major you pinned is deprecated; Sunset is the date it stops working. |
X-Deprecation-Message | The owner’s note on the deprecation, when there is one. |
X-Extractor-Id-Renamed | The owner changed their username; the header names the current id. |
X-Credit-Balance | Your balance in USD after this request (live keys only). |
A small helper that turns them into log lines:
import logging
log = logging.getLogger("scraper")
def check_headers(resp):
version = resp.headers.get("X-Extractor-Version")
if resp.headers.get("Deprecation"):
log.warning(
"extractor version %s is deprecated, sunset %s: %s",
version,
resp.headers.get("Sunset"),
resp.headers.get("X-Deprecation-Message", ""),
)
renamed = resp.headers.get("X-Extractor-Id-Renamed")
if renamed:
log.warning("extractor renamed, update your id to %s", renamed)
balance = resp.headers.get("X-Credit-Balance")
if balance is not None and float(balance) < 5:
log.warning("credit balance is low: %s USD", balance)
return version
The 5 is your own threshold, not an API value. Storing X-Extractor-Version next to each row also tells you later which version produced which data.
Handling web scraping API errors in Python
Errors come in two body shapes, and a client should read both:
- Request, fetch and billing errors:
{ "success": false, "error": "...", "errors": [{ "code", "message", "path"? }], "requestId": "..." }. - Version and job answers (
pin_required, a yanked version, a job that failed):{ "success": false, "error": "...", "details": { "code": "..." } }.
One function gets the code out of either:
def error_code(body):
errors = body.get("errors") or []
if errors:
return errors[0].get("code")
return (body.get("details") or {}).get("code")
The codes your client will meet most often:
| Status | Code | What to do |
|---|---|---|
| 400 | validation_error, pin_required, invalid_pin | Fix the request; never retry as is. |
| 401 | unauthorized | Check the key. |
| 402 | insufficient_balance | Top up; the body has top_up_url. Nothing was charged. |
| 404 / 410 | not_found, version_yanked | Wrong id, or the exact version was withdrawn; the message names a replacement when one exists. |
| 422 | required_fields_missing | The page was fetched but a required field was empty; fields lists which. |
| 429 | rate_limited, too_many_queued | Wait and retry. |
| 502 | target_error | The target page answered with an error status. |
| 502 | upstream_error | The scraping service failed before it fetched the page. |
| 503 | queue_timeout, no_provider_available | Wait for Retry-After and retry. |
| 504 | upstream_timeout | The fetch timed out. |
The required fields post covers the 422 case in depth.
Which failures were charged
The rule is simple: a request that fails after the page was fetched is charged in full, and failures before any fetch are free. You do not have to guess which side of the line a failure fell on: a charged error body carries charged: true, the cost and a note. Validation errors, 402, 429, queue_timeout, no_provider_available and upstream_error are not charged.
This decides your retry policy. Retrying a free failure costs nothing. Retrying a charged failure (a target_error on a page that returned 404, say) is a new request with a new charge, and the page will probably answer the same way.
Retries with Retry-After
Retry only what is free and likely to pass on a second try, and respect Retry-After when the API sends it (429 for too many queued requests and 503 do; when it is missing, back off yourself):
import time
RETRYABLE = {"rate_limited", "too_many_queued", "queue_timeout",
"no_provider_available", "upstream_error"}
class ExtractError(Exception):
def __init__(self, status, code, body):
super().__init__(f"{status} {code}: {body.get('error')}")
self.status = status
self.code = code
self.charged = body.get("charged", False)
self.body = body
def extract(target_url, extractor_id, max_attempts=4):
for attempt in range(1, max_attempts + 1):
resp = session.get(
f"{API_URL}/api/extractor/extract",
params={"target_url": target_url, "extractor_id": extractor_id},
timeout=(10, 120),
)
body = resp.json()
if resp.status_code == 200:
check_headers(resp)
return body["result"]
if resp.status_code == 202:
check_headers(resp)
return wait_for_job(body["result"])
code = error_code(body)
retry = code in RETRYABLE and not body.get("charged")
if not retry or attempt == max_attempts:
raise ExtractError(resp.status_code, code, body)
delay = int(resp.headers.get("Retry-After", 2 ** attempt))
time.sleep(delay)
Branch on the code, never on the message text: messages are written for people and may change, the codes are the contract.
The 202 path: polling an async job
When a request has waited 30 seconds and no scraping capacity has become free, the API does not fail it. It accepts it as an async job and answers 202:
{
"success": true,
"result": {
"job_id": "job_...",
"status": "queued",
"status_url": "https://api.extracthub.io/api/extractor/jobs/job_...",
"result_url": "https://api.extracthub.io/api/extractor/jobs/job_.../result",
"extractor_version": "1.2.0",
"created_at": "2026-11-22T08:00:30.000Z"
}
}
The same URL is in the Location header, and Retry-After suggests when to poll. The job runs as soon as capacity is free. Polling the status URL returns the job with status queued, running, completed, failed or cancelled; a completed job carries result, exactly the result a 200 would have had, and a failed one carries error with a code and a message:
def wait_for_job(job, max_wait_s=900):
deadline = time.monotonic() + max_wait_s
while time.monotonic() < deadline:
resp = session.get(job["status_url"], timeout=(10, 30))
resp.raise_for_status()
job = resp.json()["result"]
if job["status"] == "completed":
return job["result"]
if job["status"] in ("failed", "cancelled"):
raise ExtractError(422, job["error"]["code"], {"error": job["error"]["message"]})
time.sleep(int(resp.headers.get("Retry-After", 10)))
raise TimeoutError(f"job {job['job_id']} still {job['status']}")
max_wait_s is your choice. A few things to know about jobs:
- Charging follows the realtime rule: a job is charged when it completes, or when it fails after the page was fetched. Credit for it is held when it is created, which is why
X-Credit-Balanceon a 202 is already lower. - Cancelling:
POST /api/extractor/jobs/{id}/cancelcancels a job that has not started; a cancelled job is not charged. - Results expire 7 days after completion (
expires_at). The status stays readable;result_urlthen answers 410. - No polling at all: pass
webhook_url(HTTPS) with the request and you getjob.completedorjob.failedif it becomes a job. Verify the signature on your side, as shown in verify webhook signatures.
If your code cannot handle a job (a request handler that must answer now), opt out with async_fallback=false. A request still waiting after 30 seconds then gets 503 queue_timeout with Retry-After, which the retry loop above already handles.
POST when the target needs a body
Use POST /api/extractor/extract with a JSON body when the target page itself needs a POST body or custom headers. The fields are nested differently:
resp = session.post(
f"{API_URL}/api/extractor/extract",
json={
"extractor_id": "@you/example-search@1",
"target": {"url": "https://www.example.com/search", "body": "q=headphones"},
"async_fallback": True,
},
timeout=(10, 120),
)
Custom target headers are only sent when the extractor version fetches the page directly (without the proxy); through the scraping proxy they are dropped. Responses, headers and errors are the same as for GET.
Test the client without spending credit
Run everything above with a test key first. A test key answers from sample results, never calls the scraping service and never moves credit, and a live key cannot send the extra sandbox_scenario parameter (400). Each scenario exercises one branch of the client:
for scenario in ("success", "failed", "timeout_to_job", "insufficient_credit"):
resp = session.get(
f"{API_URL}/api/extractor/extract",
params={
"target_url": "https://www.example.com/p/123",
"extractor_id": "@you/example-product@1",
"sandbox_scenario": scenario,
},
timeout=(10, 120),
)
print(scenario, resp.status_code, error_code(resp.json()))
failed answers 502 upstream_error, timeout_to_job answers 202 with a sandbox job, and insufficient_credit answers 402. The web scraping sandbox post lists every scenario and where sandbox results come from.
When one URL at a time is the wrong shape
A loop of realtime calls is fine for tens of pages. For thousands, send them to the Batch API in one request and read the results as NDJSON pages, as described in batch web scraping. The same pinned extractor, the same credit rules, and no client-side retry loop to maintain.
FAQ
How do I call a web scraping API from Python?
Send a GET request to /api/extractor/extract with your API key in the X-API-Key header, the page as target_url and a pinned extractor_id such as @you/slug@1. The requests library is enough; the extracted fields come back under result.extracted.
Why does the API answer 202 instead of the data?
When no scraping capacity becomes free within 30 seconds, the request is accepted as an async job. The 202 body has job_id, status_url and result_url; poll the status URL until the job is completed, or pass async_fallback=false to get a 503 queue_timeout instead.
Which errors should my Python client retry?
Retry 429, 503 and upstream_error, which are free: wait for the Retry-After header when it is sent, else back off yourself. Do not retry a body with charged: true automatically; the page was already fetched, so a retry is a new charge.
How can I test my Python scraping code without spending credit?
Use a test API key (exth_test_...). It answers from sample results, never fetches a page and never uses credit, and the sandbox_scenario parameter simulates failures and the 202 job path.
Related
- Build a job listings scraper: list pages, JobPosting JSON and dedupe by URL: Build a job listings scraper that returns structured JSON: job URLs from list pages, JobPosting fields and ISO dates from each job page, and dedupe by URL.
- Build a price monitoring scraper: product fields, daily runs and change detection: Build a price monitoring scraper: a product extractor with typed prices, daily batch or scheduled runs, a signed webhook and change detection in your code.
- Use ready-made web scrapers instead of writing one: find, check and pin a public extractor: Use ready-made web scrapers instead of writing one: find a public extractor, read its fields, price tier and health, pin a version and call it with your key.
- Agent skill: install the extractor builder skill for Claude Code
- MCP server: connect Claude Code, Cursor or any MCP client
- API reference: realtime extract, async jobs and the Batch API
- Web scraper catalog: public extractors you can call today