Ask for the fields your application needs
Structured extraction appends a typed data object to a single Data API request. You can specify fields like title, numeric price, and URL, or utilize an existing active recipe. Design the schema with the downstream use case in mind: attempting to store every possible field complicates validation and upkeep.
Supported scalar types include string, number, integer, boolean, date, and URL. Lists use multiple; object collections describe repeated records with scalar fields. Nested object collections are not supported.
Submit a supported single-request schema
This request asks for a product title, numeric price, currency, and availability. Replace the example URL with a permitted page that visibly contains those fields; the schema does not guarantee that a target returns them. Use a Data API key with scrape:write and requests:read scopes, and generate a fresh idempotency key for each new observation. Structured extraction is available on individual Data API requests, while Data API batches accept raw scrape jobs only.
curl --request POST "https://api.runharvester.com/api/v1/data/requests" \
--header "X-API-Key: $RUNHARVESTER_API_KEY" \
--header "Idempotency-Key: $RUNHARVESTER_IDEMPOTENCY_KEY" \
--header "Content-Type: application/json" \
--data '{
"url": "https://example.com/product",
"mode": "auto",
"extraction": {
"fields": [
{ "name": "title", "type": "string", "required": true },
{ "name": "price", "type": "number", "required": true },
{ "name": "currency", "type": "string", "required": true },
{ "name": "availability", "type": "string", "required": true }
]
}
}'Validate the returned data and extraction state
The complete Python example submits the extraction request, polls it, fetches the result, validates the fields, and prints returned IDs, structured data, extraction state, and expiry. It omits raw HTML and text. Output values depend on the permitted target page and are intentionally not hard-coded. Page acquisition and extraction have separate outcomes, so handle a failed extraction even if page retrieval completed.
An early result request returns 409 RESULT_NOT_READY; continue polling. Results are retained for seven days and can expire with 410 RESULT_EXPIRED. Other non-success responses use the documented PublicError body. Validate currency, target identity, and any business rules your schema does not represent before storing values.
import json
import os
import random
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen
API = "https://api.runharvester.com/api/v1/data"
API_KEY = os.environ["RUNHARVESTER_API_KEY"]
IDEMPOTENCY_KEY = os.environ["RUNHARVESTER_IDEMPOTENCY_KEY"]
PRODUCT_URL = os.environ["RUNHARVESTER_PRODUCT_URL"]
HTTP_TIMEOUT_SECONDS = 30
CLIENT_WAIT_LIMIT_SECONDS = 240
MAX_POLL_DELAY_SECONDS = 10
def call(method, path, payload=None):
headers = {"X-API-Key": API_KEY}
body = None
if payload is not None:
headers["Idempotency-Key"] = IDEMPOTENCY_KEY
headers["Content-Type"] = "application/json"
body = json.dumps(payload).encode()
request = Request(API + path, data=body, method=method, headers=headers)
with urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response:
return response.status, json.load(response)
payload = {
"url": PRODUCT_URL,
"mode": "auto",
"extraction": {
"fields": [
{"name": "title", "type": "string", "required": True},
{"name": "price", "type": "number", "required": True},
{"name": "currency", "type": "string", "required": True},
{"name": "availability", "type": "string", "required": True},
]
},
}
try:
status_code, submission = call("POST", "/requests", payload)
if status_code != 202:
raise RuntimeError("Unexpected submission status: " + str(status_code))
request_id = submission["id"]
print("202 submission:", json.dumps(submission, indent=2))
deadline = time.monotonic() + CLIENT_WAIT_LIMIT_SECONDS
delay = 1
while time.monotonic() < deadline:
status_code, state = call("GET", "/requests/" + request_id)
if status_code != 200:
raise RuntimeError("Unexpected polling status: " + str(status_code))
print("200 status:", json.dumps(state, indent=2))
if state["status"] == "completed":
break
if state["status"] in {"failed", "cancelled"}:
raise RuntimeError("Request ended without an extractable result: " + json.dumps(state))
time.sleep(delay + random.random() * delay * 0.2)
delay = min(delay * 2, MAX_POLL_DELAY_SECONDS)
else:
raise TimeoutError("Request did not complete before the client deadline")
status_code, result = call("GET", "/requests/" + request_id + "/result")
if status_code != 200:
raise RuntimeError("Unexpected result status: " + str(status_code))
extraction = result.get("extraction")
if not isinstance(extraction, dict) or extraction.get("status") != "completed":
raise RuntimeError("Extraction did not complete: " + json.dumps(extraction))
data = result.get("data")
if not isinstance(data, dict):
raise ValueError("Expected a structured data object")
if not isinstance(data.get("title"), str) or not data["title"].strip():
raise ValueError("Missing required title")
price = data.get("price")
if isinstance(price, bool) or not isinstance(price, (int, float)):
raise ValueError("Expected price to be numeric")
if not isinstance(data.get("currency"), str) or not data["currency"].strip():
raise ValueError("Missing required currency")
if not isinstance(data.get("availability"), str) or not data["availability"].strip():
raise ValueError("Missing required availability")
response_view = {
"id": result["id"],
"data": data,
"extraction": extraction,
"expires_at": result["expires_at"],
}
print("200 extraction result:", json.dumps(response_view, indent=2))
except HTTPError as error:
body = error.read().decode("utf-8")
try:
error_json = json.loads(body)
except json.JSONDecodeError:
error_json = {"body": body}
print("HTTP error:", json.dumps({"status": error.code, "response": error_json}, indent=2))
raise