Crawling a site to Markdown for RAG
On this page
This recipe turns a documentation site into Markdown files ready for chunking and embedding, with provenance kept next to every page.
Cost:
/v1/map: each fetch that returned real content (robots.txt, sitemap files, the start page) at the page price, at most 12 fetches. Usually under $0.0015./v1/crawls/batch: $0.00011 per page at Standard, $0.0011 at Rendered, $0.003 at Protected. Pages that aren't real content (challenge pages, login walls, error pages, empty shells) cost $0. 300 Standard pages is $0.033.
You need: Python 3.9+, requests, DATAFORGAIO_API_KEY.
import json
import os
import pathlib
import re
import time
import requests
BASE = "https://api.dataforgaio.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DATAFORGAIO_API_KEY']}"} # Crawl API: Bearer or X-API-Key
SITE = "https://docs.example.com/"
OUT = pathlib.Path("corpus")
LIMIT = 300
def post(path, payload):
while True:
res = requests.post(f"{BASE}{path}", headers=HEADERS, json=payload, timeout=180)
if res.status_code == 429:
time.sleep(int(res.headers.get("Retry-After", "5")))
continue
body = res.json()
if res.status_code >= 400 and body.get("status") == "error":
raise SystemExit(f"{path}: {body['error']}")
return body
# 1. Find the pages.
site_map = post("/map", {"url": SITE, "limit": LIMIT, "search": "/guides/", "max_level": "rendered"})
urls = [u["url"] for u in site_map["urls"]]
print(f"map: {len(urls)} URLs from {len(site_map['sitemaps'])} sitemaps, billed ${site_map['billed_usd']}")
# 2. Crawl them in batches of 100.
jobs = []
for i in range(0, len(urls), 100):
job = post("/crawls/batch", {
"targets": [{"url": u} for u in urls[i:i + 100]],
"output_format": "markdown",
"max_level": "rendered", # never pay the Protected price on a docs site
"max_cost": 0.0011,
})
jobs.append(job["job_id"])
print("queued", job["job_id"], job["tasks_count"])
# 3. Wait for each job and save pages with their receipts.
OUT.mkdir(exist_ok=True)
total = 0.0
for job_id in jobs:
delay = 2
while True:
res = requests.get(f"{BASE}/crawls/{job_id}", headers=HEADERS, timeout=120).json()
if res["job_status"] == "completed":
break
time.sleep(delay)
delay = min(delay * 1.5, 15)
for task in res["tasks"]:
total += task["cost"]
receipt = task.get("receipt") or {}
if task["status"] != "completed" or receipt.get("content_check") != "substantive":
print("skip", receipt.get("source_url"), task["status"], task["status_message"])
continue
slug = re.sub(r"[^a-z0-9]+", "-", receipt["source_url"].lower()).strip("-")[:120]
(OUT / f"{slug}.md").write_text(task["content"]["markdown"])
(OUT / f"{slug}.json").write_text(json.dumps({
"title": task["content"]["title"],
"source_url": receipt["source_url"],
"fetched_at": receipt["fetched_at"],
"content_sha256": receipt["content_sha256"],
"robots_txt": receipt["robots_txt"],
"ai_use_signal": receipt["ai_use_signal"],
"fetch_level": receipt["fetch_level"],
"billed_usd": receipt["billed_usd"],
"receipt_id": receipt["receipt_id"],
}, indent=2))
print(f"done: {len(list(OUT.glob('*.md')))} pages, ${total:.4f}")How it works
- Map.
POST /v1/mapreads robots.txt, up to 10 sitemap files and the links on the start page, and returns up tolimitURLs (max 5,000) as{url, source, lastmod, crawler_allowed}.searchkeeps URLs containing that text. It doesn't crawl beyond the start page. - Batch.
POST /v1/crawls/batchqueues up to 100 targets and returns ajob_idat once. If any URL is invalid, the whole batch is refused (422) and nothing is billed. - Collect.
GET /v1/crawls/{job_id}returnsjob_status(queued,processing,completed) and every task with its content and receipt. Reads are free. Instead of polling, passwebhook_url(https) and we'll post the finished job to you. See Handling webhooks securely.
Respecting site signals
Every receipt records robots_txt and ai_use_signal, and each map URL carries crawler_allowed. robots.txt is recorded, not enforced, so the decision is yours. To skip pages a site has reserved from AI use, filter before you index:
keep = receipt["robots_txt"] != "disallowed" and receipt["ai_use_signal"] not in ("reserved",)Into your index
The .json sidecar keeps provenance with each document. When you chunk, copy source_url, fetched_at and content_sha256 onto every chunk so an answer can cite exactly which fetch it came from. The Python SDK's DataForGAIOLoader (LangChain) and DataForGAIOReader (LlamaIndex) do this for you; see SDKs.
Reference: POSTMap a site, POSTCrawl a batch, GETGet a crawl.