Platform / Capabilities

Structured data extraction from web pages

Request typed fields from one web page, inspect extraction status, and validate returned data before using it.

By · Updated

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.

Request / responseExample
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.

Request / responseExample
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

A few useful answers

Common questions

Can extraction return a list of products?

Yes. An object collection employs type object, sets multiple to true, and includes a fields list outlining its scalar attributes. Nested object collections aren't allowed. Field names need to be unique at their level; check current limits before creating a complex schema.

Read the documentation
What is an extraction recipe?

A recipe serves as reusable extraction settings. Use an owned active recipe if you need to run the same extraction again. When the target layout shifts, test sample pages and confirm required fields; relying solely on reuse doesn't ensure accurate data.

Read the documentation
Can I submit structured extraction in a Data API batch?

Data API batches accept raw scrape jobs only. Submit structured extraction as individual requests.

Read the documentation
Is structured extraction billed separately?

The documented pricing model includes structured extraction in request pricing. The selected route can affect the total request cost. Check the returned billing metadata and current billing documentation before estimating a workload.

Read the documentation

Put it to work

Start with one real request.

Inspect the result. Refine your workflow. Choose a plan for your workload.