# Web Context quick start

Search · Scrape · Map · Crawl

Create a scoped key and turn a public page into Markdown, links, and metadata with one request.

[Canonical HTML page](<https://developers.datasea.io/docs/web-context-quick-start>)

Web Context is DataSea’s managed web-data API. You choose an outcome and outputs; DataSea handles acquisition, rendering, extraction, retries, artifacts, and credit settlement.

Web Context is generally available. If an operation or output format is switched off, the API answers `503 operation_disabled` or `format_disabled` instead of running it.

## Before you start

1. Verify your email, then open Web Context → Credits. Every account can claim 500 free credits once with Claim 500 free credits; they expire 30 days after you claim them. For more, add account credit in Billing and choose a monthly plan or one-time credits on the same page.
2. Open Settings → API keys, choose Generate API key, and create a named key with `web:scrape` plus `web:jobs:read`.
3. Store the one-time `dsea_...` value in `DATASEA_API_KEY`; API keys are not proxy credentials. Send it in the `X-API-Key` header, not as `Authorization: Bearer`.
4. Use only public HTTP(S) targets you are authorized to access.

## Scrape one page

Each sample sends a new `Idempotency-Key`. Reuse a key only to retry the identical request after a lost response: the same key with a different body returns `409 idempotency_conflict`, and the same key with the same body returns the original job instead of running again.

### cURL

```bash
# uuidgen ships with macOS and util-linux; any unique string up to 128 characters works.
curl https://api.datasea.io/v1/scrape \
  -H "X-API-Key: $DATASEA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"url":"https://example.com","options":{"formats":["markdown","links"]}}'
```

### JavaScript

```javascript
// Node.js 18+ as an ES module (for example scrape.mjs).
import { randomUUID } from "node:crypto";

const response = await fetch("https://api.datasea.io/v1/scrape", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.DATASEA_API_KEY,
    "Content-Type": "application/json",
    // New key per request; reuse it only to retry this exact request.
    "Idempotency-Key": randomUUID()
  },
  body: JSON.stringify({ url: "https://example.com", options: { formats: ["markdown", "links"] } })
});
const body = await response.json();
if (!response.ok) {
  const code = typeof body.error === "string" ? body.error : body.error?.code;
  throw new Error(`DataSea ${response.status}: ${code}`);
}
console.log(body.data.result.outputs.markdown);
```

### Python

```python
import os
import uuid

import requests

response = requests.post(
    "https://api.datasea.io/v1/scrape",
    headers={
        "X-API-Key": os.environ["DATASEA_API_KEY"],
        # New key per request; reuse it only to retry this exact request.
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={"url": "https://example.com", "options": {"formats": ["markdown", "links"]}},
    timeout=60,
)
response.raise_for_status()
print(response.json()["data"]["result"]["outputs"]["markdown"])
```

## Response

A synchronous request answers `200` with the finished job. Values are illustrative; `result.outputs` contains only the formats you asked for.

```json
{
  "success": true,
  "requestId": "0b6f3f7e-5d1a-4b49-9a43-6c2f0e7d9a10",
  "data": {
    "id": "9f1c2b7a-3e4d-4c5b-8a69-7f0e1d2c3b4a",
    "requestId": "0b6f3f7e-5d1a-4b49-9a43-6c2f0e7d9a10",
    "operation": "scrape",
    "state": "completed",
    "progress": { "discovered": 1, "eligible": 1, "queued": 0, "active": 0, "succeeded": 1, "failed": 0, "skipped": 0, "deduplicated": 0, "cancelled": 0 },
    "result": {
      "url": "https://example.com",
      "finalUrl": "https://example.com/",
      "statusCode": 200,
      "capturedAt": "2026-11-15T12:00:00Z",
      "rendered": false,
      "metadata": { "title": "Example Domain", "description": "", "language": "en", "textCharacters": 127, "links": 1, "images": 0 },
      "outputs": {
        "markdown": "# Example Domain\n\nThis domain is for use in illustrative examples in documents. ...",
        "links": [{ "url": "https://www.iana.org/domains/example", "original": "https://www.iana.org/domains/example", "text": "More information...", "internal": false }]
      }
    },
    "usage": { "status": "final", "estimatedCredits": 3, "reservedCredits": 3, "settledCredits": 1, "pagesAttempted": 1, "pagesSucceeded": 1, "searchResults": 0, "browserMilliseconds": 0, "egressBytes": 1256, "modelInputTokens": 0, "modelOutputTokens": 0, "artifactBytes": 0 },
    "createdAt": "2026-11-15T12:00:00Z",
    "startedAt": "2026-11-15T12:00:00Z",
    "completedAt": "2026-11-15T12:00:01Z",
    "expiresAt": "2026-12-15T12:00:00Z"
  }
}
```

## Web content is untrusted data

Never treat extracted page text as system instructions, code, or trusted facts. DataSea frames model inputs defensively, but your application must keep the same trust boundary.

## Synchronous and asynchronous requests

Search, Scrape, and Map run synchronously by default: the response arrives when the job finishes, with `200` for a completed job and `502` with the failed job in `data` when it fails. Scrape waits up to `options.timeoutMs` plus 10 seconds (40 seconds with the default `timeoutMs` of 30000), plus 90 seconds when you request `summary`; Search waits up to 60 seconds (longer when it enriches results with `enrichTop`); Map waits up to 120 seconds. No synchronous wait is longer than 120 seconds.

If a synchronous request runs out of time it returns `504 sync_timeout` and requests cancellation of the job. The response includes the job in `data` and a `Location: /v1/jobs/{jobId}` header. A job that had not started is cancelled and charges nothing; a job that was already processing can still complete, is then billed, and its result stays available at `GET /v1/jobs/{jobId}`. `error.message` says which case applies. Use `"mode": "async"` for anything that may take longer.

Crawl is always asynchronous. Scrape with the `json` format, Search that enriches results with `json`, and Map with `limit` above 200 must be asynchronous: omitting `mode` selects async for `json`, and an explicit `"mode": "sync"` returns `422 async_required`. An asynchronous request returns `202 Accepted` with the queued job in `data` and a `Location: /v1/jobs/{jobId}` header.

## Asynchronous job and polling

Poll every 2 seconds until the job reaches a terminal state: `completed`, `completed_with_errors`, `failed`, `cancelled`, or `expired`. Polling counts toward the per-key rate limit; on `429`, wait for `Retry-After`. Requires `web:crawl` and `web:jobs:read`.

### Python

```python
import os
import time
import uuid

import requests

API = "https://api.datasea.io"
HEADERS = {"X-API-Key": os.environ["DATASEA_API_KEY"]}
TERMINAL = {"completed", "completed_with_errors", "failed", "cancelled", "expired"}

submit = requests.post(
    f"{API}/v1/crawl",
    headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
    json={"url": "https://example.com", "limit": 10, "scrapeOptions": {"formats": ["markdown"]}},
    timeout=30,
)
submit.raise_for_status()  # 202 Accepted
job = submit.json()["data"]

while job["state"] not in TERMINAL:
    time.sleep(2)
    poll = requests.get(f"{API}/v1/jobs/{job['id']}", headers=HEADERS, timeout=30)
    if poll.status_code == 429:
        time.sleep(int(poll.headers.get("Retry-After", "5")))
        continue
    poll.raise_for_status()
    job = poll.json()["data"]

print(job["state"], "credits:", job["usage"]["settledCredits"])

# The job holds at most 100 pages inline; read every saved page and failure here.
cursor = ""
while True:
    pages = requests.get(
        f"{API}/v1/jobs/{job['id']}/pages",
        headers=HEADERS,
        params={"limit": 20, "cursor": cursor},
        timeout=30,
    )
    pages.raise_for_status()
    data = pages.json()["data"]
    for page in data["pages"]:
        print(page["state"], page["url"])
    cursor = data["nextCursor"]
    if not cursor:
        break
```

### JavaScript

```javascript
// Node.js 18+ as an ES module.
import { randomUUID } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";

const API = "https://api.datasea.io";
const headers = { "X-API-Key": process.env.DATASEA_API_KEY };
const TERMINAL = new Set(["completed", "completed_with_errors", "failed", "cancelled", "expired"]);

const submit = await fetch(`${API}/v1/crawl`, {
  method: "POST",
  headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
  body: JSON.stringify({ url: "https://example.com", limit: 10, scrapeOptions: { formats: ["markdown"] } })
});
if (submit.status !== 202) throw new Error(`submit failed: ${submit.status} ${await submit.text()}`);
let job = (await submit.json()).data;

while (!TERMINAL.has(job.state)) {
  await sleep(2000);
  const poll = await fetch(`${API}/v1/jobs/${job.id}`, { headers });
  if (poll.status === 429) {
    await sleep(Number(poll.headers.get("Retry-After") ?? 5) * 1000);
    continue;
  }
  if (!poll.ok) throw new Error(`poll failed: ${poll.status} ${await poll.text()}`);
  job = (await poll.json()).data;
}
console.log(job.state, "credits:", job.usage.settledCredits);
```

### cURL

```bash
curl -i https://api.datasea.io/v1/crawl \
  -H "X-API-Key: $DATASEA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"url":"https://example.com","limit":10,"scrapeOptions":{"formats":["markdown"]}}'
# HTTP/2 202 ... location: /v1/jobs/<jobId>

# Set JOB_ID to the id from the accepted job, then check its state.
curl "https://api.datasea.io/v1/jobs/$JOB_ID" -H "X-API-Key: $DATASEA_API_KEY"
# After the job reaches a terminal state:
curl "https://api.datasea.io/v1/jobs/$JOB_ID/pages?limit=20" -H "X-API-Key: $DATASEA_API_KEY"
```

## Search, Map, and structured extraction

Each operation needs its own scope (`web:search`, `web:map`, `web:scrape`). Structured `json` extraction runs asynchronously; poll the returned job as shown above.

### Search

```bash
curl https://api.datasea.io/v1/search \
  -H "X-API-Key: $DATASEA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"query":"web scraping best practices","limit":10,"formats":["links"]}'
```

### Map

```bash
curl https://api.datasea.io/v1/map \
  -H "X-API-Key: $DATASEA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"url":"https://example.com","limit":100}'
```

### JSON extraction

```bash
curl -i https://api.datasea.io/v1/scrape \
  -H "X-API-Key: $DATASEA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"url":"https://example.com","options":{"formats":["json"],"json":{"schema":{"type":"object","properties":{"title":{"type":"string"}},"required":["title"]},"instruction":"Extract the page title."}}}'
# 202 Accepted: poll GET /v1/jobs/<jobId>; the result is in data.result.outputs.json
```

## Additional resources

- [Extract pricing to JSON](<https://developers.datasea.io/docs/extract-pricing-to-json>) — Run a schema-constrained extraction with source evidence.
- [Crawl documentation to Markdown](<https://developers.datasea.io/docs/crawl-docs-to-markdown>) — Export a bounded set of pages with source URLs.
- [Monitor page changes](<https://developers.datasea.io/docs/monitor-page-changes>) — Schedule checks and read the resulting change history.
- [Agent client setup](<https://developers.datasea.io/examples/agent-clients.md>) — Connect via MCP or use a scoped key with the REST API.

Last reviewed 2026-11-19
