Most teams come to Scwrap with scrapers they already run: a TypeScript function around fetch, a Python script around requests, a Playwright job on a cron. This page moves one onto Scwrap. The scraping logic survives mostly as it is; what changes is where its inputs, outputs, failures and outside services are declared.
It assumes your team has an instance and a Scraper repository set up as in Installation. The worked example is small on purpose. Your real Scrapers stay in your own private repository and are deployed to your own instance, as this one is.
What goes where
| In your scraper today | In Scwrap |
|---|---|
| Function parameters, CLI flags | The Definition's input schema. Invalid input never reaches your code. |
| The object or row it returns | The Definition's output schema. The instance checks every item against it. |
throw, raise, status-code checks | The Definition's error union: Shared errors such as Blocked and RateLimited, plus your own Schema.TaggedErrors. |
fetch, axios, requests | The HttpClient Capability, through the HTTP helpers. |
A proxy agent and a proxy password in .env | The ProxiedHttpClient Capability with a proxy route. The instance's front desk holds the password. |
| Puppeteer, Playwright, Selenium | The Browser Capability. |
| A captcha service call | The TextCaptchaSolver Capability. |
Retry loops and sleep | Download's retries, or Effect.retry with a Schedule. |
console.log, log files | Spans: Effect.fn names a step, Effect.annotateCurrentSpan adds context. |
| Writing to a file or a database | Nothing. The instance stores each Run's items as its Result, and callers read them with @scwrap/client, HTTPS or MCP. |
| A cron entry | A scheduler outside Scwrap, such as a GitHub Actions cron, that starts each Run with a run token (Scheduling Runs). |
The script's main | The Release: it picks the Implementation and provides its Capabilities. |
The code that parses the site's answer and maps it to your record is the part you keep.
The scraper you start from
This scraper reads the top stories from the Hacker News API. It fetches the list of IDs, then each item, and skips anything that is not a live story.
Example (The scraper before the port, in TypeScript)
const base = "https://hacker-news.firebaseio.com/v0";
export interface Story {
author: string;
id: number;
points: number;
postedAt: string;
title: string;
url: string | null;
}
export async function topStories(limit = 30): Promise<Story[]> {
const response = await fetch(`${base}/topstories.json`);
if (!response.ok) throw new Error(`topstories: HTTP ${response.status}`);
const ids: number[] = await response.json();
const stories: Story[] = [];
for (const id of ids.slice(0, limit)) {
const item = await (await fetch(`${base}/item/${id}.json`)).json();
if (!item || item.type !== "story" || item.deleted || item.dead) continue;
stories.push({
author: item.by,
id: item.id,
points: item.score,
postedAt: new Date(item.time * 1000).toISOString(),
title: item.title,
url: item.url ?? null,
});
}
return stories;
}Example (The same scraper in Python)
from datetime import datetime, timezone
import requests
BASE = "https://hacker-news.firebaseio.com/v0"
def top_stories(limit=30):
response = requests.get(f"{BASE}/topstories.json", timeout=30)
response.raise_for_status()
stories = []
for story_id in response.json()[:limit]:
item = requests.get(f"{BASE}/item/{story_id}.json", timeout=30).json()
if not item or item.get("type") != "story" or item.get("deleted") or item.get("dead"):
continue
posted = datetime.fromtimestamp(item["time"], timezone.utc)
stories.append({
"author": item["by"],
"id": item["id"],
"points": item["score"],
"postedAt": posted.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
"title": item["title"],
"url": item.get("url"),
})
return storiesBoth work until something goes wrong. A 429 is an untyped exception, an item without a title becomes a record with undefined in it, nothing limits limit, and one failure on item 29 loses the 28 stories already read.
Create packages/hn-top-stories the same way as Your first Scraper: copy its package.json with your own package name, here @acme/hn-top-stories, and the three config files.
Write the Definition
The Story interface and the limit parameter become schemas, and the throw becomes a list of errors.
Example (src/story.ts)
import { Schema } from "effect";
export const TopStoriesQuery = Schema.Struct({
limit: Schema.Int.check(Schema.isBetween({ maximum: 100, minimum: 1 })),
});
export const Story = Schema.Struct({
author: Schema.NonEmptyString,
id: Schema.Int,
points: Schema.Int,
postedAt: Schema.String.check(
Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u)
),
title: Schema.NonEmptyString,
url: Schema.NullOr(Schema.String.check(Schema.isPattern(/^https?:\/\//u))),
});Example (src/definition.ts)
import {
Blocked,
RateLimited,
SchemaDrift,
Scraper,
UpstreamDown,
} from "@scwrap/domain";
import { Schema } from "effect";
import { Story, TopStoriesQuery } from "./story.js";
export { Story, TopStoriesQuery } from "./story.js";
export const TopStories = Scraper.make("hn-top-stories", {
error: Schema.Union([Blocked, RateLimited, SchemaDrift, UpstreamDown]),
input: TopStoriesQuery,
output: Story,
});Write the output schema from what your consumers rely on, not from what the site sends. If they cannot handle a story without a title, NonEmptyString makes such an item a SchemaDrift instead of a bad row in their data.
Pick the errors from what the site can do. Each Shared error tells a caller something different: Blocked and RateLimited mean wait or change the route, UpstreamDown means try later, SchemaDrift means the Scraper needs repair. A failure your callers must tell apart from these, such as a login the site refused, becomes your own error.
Write the Implementation
The loop becomes a stream, and fetch becomes Download.json.
Example (src/api.ts)
import { decodeScrapedRecord, Download, Scraper } from "@scwrap/domain";
import { DateTime, Effect, Predicate, Schema, Stream } from "effect";
import { TopStories } from "./definition.js";
import { Story } from "./story.js";
export const hackerNewsOrigin = "https://hacker-news.firebaseio.com";
const Item = Schema.NullOr(
Schema.Struct({
by: Schema.optionalKey(Schema.String),
dead: Schema.optionalKey(Schema.Boolean),
deleted: Schema.optionalKey(Schema.Boolean),
id: Schema.Int,
score: Schema.optionalKey(Schema.Int),
time: Schema.Int,
title: Schema.optionalKey(Schema.String),
type: Schema.String,
url: Schema.optionalKey(Schema.String),
})
);
const readStory = Effect.fn("HackerNews.readStory")(function* readStory(
id: number
) {
yield* Effect.annotateCurrentSpan("story.id", id);
const item = yield* Download.json(
`${hackerNewsOrigin}/v0/item/${id}.json`,
Item
);
if (
item === null ||
item.type !== "story" ||
item.deleted === true ||
item.dead === true
) {
return null;
}
return yield* decodeScrapedRecord(Story)(
Effect.succeed({
author: item.by,
id: item.id,
points: item.score,
postedAt: DateTime.formatIso(DateTime.makeUnsafe(item.time * 1000)),
title: item.title,
url: item.url ?? null,
})
);
});
export const HackerNewsApiLive = Scraper.layer(TopStories, ({ limit }) =>
Stream.fromEffect(
Download.json(
`${hackerNewsOrigin}/v0/topstories.json`,
Schema.Array(Schema.Int)
)
).pipe(
Stream.flatMap((ids) => Stream.fromIterable(ids.slice(0, limit))),
Stream.mapEffect(readStory, { concurrency: 4 }),
Stream.filter(Predicate.isNotNull)
)
);Example (src/index.ts)
export { TopStories } from "./definition.js";
export { Story, TopStoriesQuery } from "./story.js";
export { HackerNewsApiLive, hackerNewsOrigin } from "./api.js";What moved where:
- The status check is gone.
Download.jsonmaps 401 and 403 toBlocked, 429 toRateLimitedand other failures toUpstreamDown, retries transient failures of a GET twice and times out after 30 seconds. - The
as number[]trust is gone.Itemdescribes what the site sends, and a body that does not match fails withSchemaDriftand a sample of the body. - The filter is the same condition, and
decodeScrapedRecord(Story)checks the mapped record where it is built, so a drift report names the item, not the whole Run. - The loop is
Stream.mapEffectwithconcurrency: 4: four items in flight, emitted in the order of the list. - The returned array is a stream. Items reach the instance as they are read, so a failure on item 29 still leaves the stories before it stored: a Partial Run.
new DateisDateTime. The Effect language service flags globalDate,fetchandconsolein Effect code, because they hide a Capability from the type.
HackerNewsApiLive requires one Capability, HttpClient, and its type says so:
const HackerNewsApiLive: Layer.Layer<Rpc.Handler<"hn-top-stories">, never, HttpClient.HttpClient>Test it with FakeSite
Your old scraper's real responses are the best test data. Save a few under test/fixtures/, or write the smallest bodies that expose a mistake, as here. Testing your Scraper explains the test kit.
Example (test/acceptance.test.ts)
import { expect, it } from "@effect/vitest";
import { FakeSite, ScraperTest } from "@scwrap/domain/testing";
import { Effect, Layer } from "effect";
import {
HackerNewsApiLive,
hackerNewsOrigin,
TopStories,
} from "../src/index.js";
const topStories = `${hackerNewsOrigin}/v0/topstories.json`;
const item = (id: number) => `${hackerNewsOrigin}/v0/item/${id}.json`;
const story = (id: number, fields: object = {}) =>
JSON.stringify({
by: `author${id}`,
id,
score: id * 10,
time: 1_764_500_000 + id,
title: `Story ${id}`,
type: "story",
url: `https://example.com/${id}`,
...fields,
});
it.effect("keeps top-story order, skips non-stories and stops at limit", () =>
Effect.gen(function* topStoriesInOrder() {
const site = yield* FakeSite.make({
[topStories]: "[15, 11, 12, 13, 14, 16]",
[item(11)]: JSON.stringify({ deleted: true, id: 11, time: 1, type: "story" }),
[item(12)]: "null",
[item(13)]: story(13, { type: "job" }),
[item(14)]: story(14, { url: undefined }),
[item(15)]: story(15),
[item(16)]: story(16),
});
const run = yield* ScraperTest.run(TopStories, { limit: 5 }).pipe(
Effect.provide(HackerNewsApiLive.pipe(Layer.provide(site.layer)))
);
expect(run.failure).toBeNull();
expect(run.items).toStrictEqual([
{
author: "author15",
id: 15,
points: 150,
postedAt: "2025-11-30T10:53:35.000Z",
title: "Story 15",
url: "https://example.com/15",
},
{
author: "author14",
id: 14,
points: 140,
postedAt: "2025-11-30T10:53:34.000Z",
title: "Story 14",
url: null,
},
]);
expect(yield* site.requests).not.toContain(item(16));
})
);
it.effect("reports a refused item as RateLimited", () =>
Effect.gen(function* rateLimited() {
const run = yield* ScraperTest.run(TopStories, { limit: 2 }).pipe(
Effect.provide(
HackerNewsApiLive.pipe(
Layer.provide(
FakeSite.layer({
[topStories]: "[1, 2]",
[item(1)]: story(1),
[item(2)]: 429,
})
)
)
)
);
expect(run.failure?._tag).toBe("RateLimited");
})
);
it.effect("reports a story without a title as SchemaDrift", () =>
Effect.gen(function* drift() {
const run = yield* ScraperTest.run(TopStories, { limit: 1 }).pipe(
Effect.provide(
HackerNewsApiLive.pipe(
Layer.provide(
FakeSite.layer({
[topStories]: "[1]",
[item(1)]: story(1, { title: undefined }),
})
)
)
)
);
expect(run.failure?._tag).toBe("SchemaDrift");
expect(run.items).toStrictEqual([]);
})
);The first test lists IDs out of order and mixes a deleted item, a missing item, a job and a story without a URL inside the limit, with a valid story just past it. A port that sorts, drops the deleted check or reads one item too many fails it. The expected timestamps were computed from time outside the code under test, not copied from a run.
pnpm --filter @acme/hn-top-stories test Test Files 1 passed (1)
Tests 3 passed (3)Before you trust the tests, change ids.slice(0, limit) to ids.slice(0, limit + 1) and run them again: the first test fails. Undo the change.
Run the port once against the live site with a throwaway script, as in Run it, and compare its items with your old scraper's output for the same moment. For this example the three versions return the same records.
Release and deploy it
The old script's main becomes a Release: one module that picks the Implementation and provides its Capabilities. Add @acme/hn-top-stories with workspace:* to releases/package.json, as in Deploying to a Worker.
Example (releases/src/hn-top-stories.ts)
import { HackerNewsApiLive, TopStories } from "@acme/hn-top-stories";
import { Deployment } from "@scwrap/deploy";
import { FetchHttpClient } from "effect/http";
export default Deployment.worker({
implementation: HackerNewsApiLive,
module: import.meta.url,
scraper: TopStories,
services: FetchHttpClient.layer,
});Example (releases/src/catalog.ts)
import TopStoriesRelease from "./hn-top-stories.ts";
const catalog = [TopStoriesRelease];
export default catalog;Then build and deploy it with your instance's URL and a deployer token in the environment:
pnpm --filter '{./releases}^...' build
pnpm scwrap deploy hn-top-storiesThe instance builds the Release from its source before it deploys anything, so a type or bundling error changes nothing there. Deploying to a Worker covers the output, a pending status and deploying from CI.
Proxies, browsers and captchas
These are the parts of an old scraper that usually hold credentials: a proxy URL with a password, a browser vendor's API key, a captcha service key. In Scwrap none of them is in the Scraper or the Release. The Implementation requires a Capability, the Release names a provider, and on an instance the provider asks the front desk, which holds the vendor credentials and checks the Scraper's grant on every call.
| Old code | Implementation requires | Release provides | Grant | Guide |
|---|---|---|---|---|
A proxy agent, proxies= in requests | ProxiedHttpClient<"DE"> | apifyProxy | proxy:apify | Adding a proxy |
| Puppeteer, Playwright, Selenium | Browser | browserRun | browser:browser-run | Adding a browser |
| The same, from a given country | Browser<"FR"> | browserUse | browser:browser-use | A browser in a country |
| A captcha service | TextCaptchaSolver | A template engine, a Decision model or both | ai:workers-ai for Workers AI | Captcha solving |
When the old scraper sent its requests through a German proxy, the port keeps HackerNewsApiLive unchanged and adds a second Implementation that gets its HttpClient from a proxy route:
Example (src/proxied.ts)
import { ProxiedHttpClient } from "@scwrap/domain";
import { Layer } from "effect";
import { HackerNewsApiLive } from "./api.js";
export const HackerNewsProxiedLive = HackerNewsApiLive.pipe(
Layer.provide(ProxiedHttpClient.layerHttpClient({ country: "DE" }))
);Example (releases/src/hn-top-stories.ts with a proxy)
import { HackerNewsProxiedLive, TopStories } from "@acme/hn-top-stories";
import { Deployment } from "@scwrap/deploy";
import { apifyProxy } from "@scwrap/platform-apify";
export default Deployment.worker({
implementation: HackerNewsProxiedLive,
module: import.meta.url,
scraper: TopStories,
services: apifyProxy,
});Keeping FetchHttpClient.layer here does not compile: Missing 'ProxiedHttpClient<"DE">' in the expected Layer context. The instance owner grants proxy:apify to hn-top-stories in the grants table; without the grant every proxied request fails, and the Run with it.
A browser Implementation is the biggest rewrite. Playwright's page.goto, waitForSelector and $$eval become the Page's goto, waitFor and evaluate, the browser opens inside the stream so it closes with the Run, and BrowserError is mapped to a declared error. Adding a browser walks through all of it.
Other secrets
A credential the front desk does not cover, such as an API key for the site itself, goes under the Scraper's ID in the instance's SCRAPER_SETTINGS secret, and the Implementation reads it with Config.Redacted. Only that Scraper's Runs get it. Setting it needs an unlimited deployer token (scwrap secrets set).
Scrapers written in Python
An instance runs JavaScript only: every Release is a Worker release in its own Dynamic Worker sandbox, with no Python runtime and no Container for Scraper code. A Python scraper has two ways in.
Port it. This is the path the rest of this page takes, and the one that gets everything: typed input and output, the front desk's proxies and browsers, traces through every step, and FakeSite tests. The parsing logic usually translates line for line, as the two versions above show. Keep the Python scraper running until the port's items match its output.
| Python | TypeScript with Scwrap |
|---|---|
requests, httpx | Download.text, Download.json, Download.bytes |
| BeautifulSoup, lxml on static HTML | A parser that runs in Workers, or a browser Implementation that reads the DOM with evaluate |
playwright.sync_api | The Browser Capability |
pydantic models | Schema.Struct |
tenacity, time.sleep | Effect.retry with a Schedule |
logging | Effect.fn and Effect.annotateCurrentSpan |
Call it. Keep the Python scraper where it runs today, put it behind an HTTPS endpoint you host, and write an Implementation that calls it. The Definition and the output check stay the same, so callers cannot tell the difference.
Example (src/legacy-service.ts)
import { Download, Scraper } from "@scwrap/domain";
import { Config, Effect, Schema } from "effect";
import { HttpClientRequest } from "effect/http";
import { TopStories } from "./definition.js";
import { Story } from "./story.js";
export const LegacyServiceLive = Scraper.layer(
TopStories,
Effect.fn("LegacyService.topStories")(function* topStories(input) {
const origin = yield* Config.String("HN_SERVICE_URL").pipe(Effect.orDie);
const token = yield* Config.Redacted("HN_SERVICE_TOKEN").pipe(
Effect.orDie
);
return yield* Download.json(
HttpClientRequest.post(`${origin}/top-stories`).pipe(
HttpClientRequest.bearerToken(token),
HttpClientRequest.bodyJsonUnsafe(input)
),
Schema.Array(Story)
);
})
);Its Release provides FetchHttpClient.layer, like the first one. Know what this gives up before you choose it:
- The Python service is a second deployment you run, secure and scale yourself, on a public HTTPS address.
- The front desk cannot help it. Its proxies, browsers and captcha keys stay in the Python service's own configuration.
HN_SERVICE_URLandHN_SERVICE_TOKENlive in the Scraper's entry ofSCRAPER_SETTINGS(Other secrets).- The service answers once with every item, so a failure halfway loses them all.
Downloadwaits at most 30 seconds for that answer, so a slower scrape needs its ownHttpClientcall with a longer timeout, within the Run's maximum duration. - The trace ends at the HTTP call; what happens inside the service is not in it.
- The tests cover the call and the output check, not the scraping.
Calling a service is a bridge for the time a port takes, not a place to stay.
Porting with an agent
A port is a well-bounded job for a coding agent, and Scwrap's checks are what make its result trustworthy. Give the agent the old scraper, a few saved responses from the site, this page and the glossary, and ask it for the Definition, the Implementation, FakeSite tests built from those responses and a Release. Then:
- The types catch an undeclared error, a missing Capability in the Release and input the Definition does not allow.
- The tests catch wrong mapping, pagination and failure handling, if they include inputs where a wrong port gives a different answer. Ask the agent to plant a bug and show that a test fails.
- One live run compared with the old scraper's output catches what the saved responses did not show.
Review the Definition yourself: it is the contract your callers depend on, and the one part an agent should not guess.
Next
Calling your Scraper runs the deployed Scraper and reads its items. When the port goes live, point the old scraper's consumers at the instance and retire the old job.