Skip to content

Market Scanner — JavaScript SDK ​

Integrate with an AI assistant
Download or copy the integration prompt for Market Scanner — JavaScript SDK and paste it into Claude Code, Cursor or Copilot: it contains auth, end-to-end examples and a checklist.
Open

The JavaScript SDK does all the Market Scanner work for you: it starts the search, follows its progress in real time over the WebSocket, falls back to polling on its own if the socket drops, and gives you the result with a single await. Errors, retries, timeouts and cancellation are already handled.

Package@dokicasa/sdk (TypeScript, ESM + CommonJS, no required dependencies)
RuntimesNode 18+ and modern browsers, with a React 18+ hook and a Vue 3.3+ composable
Base URLhttps://api.dokicasa.it (production), https://api-dev.dokicasa.it (sandbox)
Authyour API token as Authorization: Bearer (the SDK sets it)
Real timeoptional, with pusher-js

Start with the sandbox

With environment: 'sandbox' the SDK uses api-dev.dokicasa.it: same APIs and socket as production, but sample data and no cost. The test token is on the Market Scanner page.

Installation ​

bash
npm install @dokicasa/sdk
# only if you want real-time updates:
npm install pusher-js

Alternatively, the same package hosted here: npm install https://docs.dokicasa.it/sdk/market-scanner/dokicasa-sdk-0.2.0.tgz.

Without a bundler you can import the ESM file directly:

html
<script src="https://cdn.jsdelivr.net/npm/pusher-js@8.4.0/dist/web/pusher.min.js"></script>
<script type="module">
  import { createClient } from 'https://docs.dokicasa.it/sdk/market-scanner/index.js';
  const dk = createClient({ token: userToken, realtime: { Pusher: window.Pusher } });
</script>

TypeScript types are included (index.d.ts).

Quick start ​

js
import { createClient } from '@dokicasa/sdk';
import Pusher from 'pusher-js';

const dk = createClient({
  token: process.env.DOKICASA_TOKEN,
  environment: 'sandbox',            // 'production' when you are ready
  realtime: { Pusher },              // optional: without it the SDK polls
});

const visura = await dk.scanner.run(
  'visura-catasto',
  { comune: 'Roma', provincia: 'RM', foglio: '123', particella: '45', tipo_visura: 'ANALITICA' },
  { onProgress: (p) => console.log(p.status, p.percentage, p.source) },
);

const pdf = await dk.scanner.downloadDocument(visura);  // { data, filename, contentType }

run starts the search and waits for it to finish. To start and wait at different times use create and then wait(id).

Searches cost money in production

Every run / create in production is a real search and uses credit. The SDK never retries a search on its own: it only retries reads.

React and Vue ​

React and Vue apps get useScanner(): it launches the search, follows it (socket + polling) and gives you UI-ready state. When the component unmounts, the wait stops by itself.

FieldContents
phaseidle, creating, running, success, error, cancelled
isRunningtrue while the search is being launched or followed
percentage0-100 for a progress bar (100 when done)
progresslatest update: Sister status, percentage, source (realtime or polling)
requestIdthe search id (store it to resume)
result / errorfinal request with results / typed error
run(type, params)launches and follows; the outcome is in the state, no exceptions
resume(id) · cancel() · reset()resume a search, stop waiting, reset
tsx
import { createClient } from '@dokicasa/sdk';
import { DokicasaProvider, useScanner } from '@dokicasa/sdk/react';
import Pusher from 'pusher-js';

const dk = createClient({ token: userToken, environment: 'sandbox', realtime: { Pusher } });

function Visura({ parcel }) {
  const scan = useScanner();
  return (
    <>
      <button disabled={scan.isRunning} onClick={() => scan.run('visura-catasto', parcel)}>Search</button>
      {scan.isRunning && <button onClick={scan.cancel}>Cancel</button>}
      <progress value={scan.percentage} max={100} />
      {scan.phase === 'success' && <a href={scan.result.result.pdf_path}>Visura ready</a>}
      {scan.error && <p role="alert">{scan.error.message}</p>}
    </>
  );
}

// <DokicasaProvider client={dk}><Visura parcel={...} /></DokicasaProvider>
vue
<!-- main.ts: createApp(App).use(DokicasaPlugin, { client: dk }) -->
<script setup lang="ts">
import { useScanner } from '@dokicasa/sdk/vue';

const props = defineProps<{ parcel: Record<string, string> }>();
const { run, cancel, phase, isRunning, percentage, result, error } = useScanner();
</script>

<template>
  <button :disabled="isRunning" @click="run('visura-catasto', props.parcel)">Search</button>
  <button v-if="isRunning" @click="cancel">Cancel</button>
  <progress :value="percentage" max="100" />
  <a v-if="phase === 'success'" :href="result?.result.pdf_path">Visura ready</a>
  <p v-if="error" role="alert">{{ error.message }}</p>
</template>
  • One search at a time per hook: for parallel searches, one useScanner() each.
  • To resume a stored search (e.g. from the URL): useScanner({ resumeId }). In Vue it accepts a ref or a getter and follows the new search when it changes.
  • The engine is ScanStore, framework-free: fine for Svelte, Angular or plain JavaScript.
  • In the browser use the individual user's token, never the partner token. Your app's domain must be enabled by Dokicasa (CORS): ask your contact, including development and staging addresses. Meanwhile, in development, go through the Vite proxy (example in the package README).

Configuration ​

Usually the token is enough. Everything else can be configured:

js
const dk = createClient({
  token: 'xxx',                       // or getToken: async () => readTheToken()
  environment: 'production',          // 'production' | 'sandbox'
  baseUrl: 'https://api.dokicasa.it', // overrides the environment (e.g. your proxy)
  timeoutMs: 60000,                   // timeout of each call
  retry: { maxRetries: 3, baseDelayMs: 500, maxDelayMs: 10000 },   // or false
  polling: { intervalMs: 2000, maxIntervalMs: 15000, backoffFactor: 1.5 },
  realtime: { Pusher, key, wsHost, wsPort, forceTLS, authEndpoint, pusherOptions }, // or false
  headers: { 'X-Correlation-Id': 'abc' },
  fetch: customFetch,
  logger: console,
  onRequest: (req) => {},             // hooks for logging and metrics
  onResponse: (res) => {},            // with status and duration
});
OptionDefaultWhat it is for
token / getTokenrequiredAuthentication. getToken is called on every request (renewable tokens).
environmentproductionPicks the API and socket URLs together, always aligned.
retry3 retries on readsOn network errors, timeouts, 429 and 5xx, honouring Retry-After.
polling2 to 15 secondsWithout a socket, polling slows down on its own.
realtimeon if pusher-js is availablefalse to poll only.
actingUser—SSO partners: calls on behalf of a user (see below).

Searches ​

Parameters are the API ones, with TypeScript types for every search type (list of types).

js
await dk.scanner.run('catasto', { comune, foglio, particella, search_catasto_type: 'F' });
await dk.scanner.run('tax-data', { tax_code: 'XXXXXX00X00X000X' });
await dk.scanner.run('ispezione-tax-data', { tax_code, provincia, comune });
await dk.scanner.run('mappa-catasto', { comune, provincia, foglio, particella, tipo_richiesta: 'ATTUALITA', tipo_foglio: 'INTERO', formato: 'A3' });

Multi-step searches. When the API needs a choice (several properties, sections, homonyms) the result has needs_selection: run again with the chosen value.

js
let r = await dk.scanner.run('visura-catasto', { ...data, enable_multi_step: true });
if (r.result.needs_selection) {
  r = await dk.scanner.run('visura-catasto', { ...data, selected_value: r.result.rows_immobili[0].value });
}

Results, documents, exports.

js
const req = await dk.scanner.get(id);                     // full request
for await (const property of dk.scanner.iterateResults(id, { filters: { categoria: ['A/2'] } })) { /* ... */ }
const { filters } = await dk.scanner.filters(id);          // available filter values
await dk.scanner.exportXls(id, { categoria: ['A/2'] });    // Excel by email (paid)
await dk.scanner.monitor(id, { models: [] });              // monitor everything (paid)

Before starting. dk.system.services() returns price and credits for every type, dk.system.health() the status of Sister. With checkHealth: true the SDK does not start the search when the service is down, so you don't spend anything.

Real time ​

With pusher-js, run and wait follow the search on the private channel private-scanner_request.{id}, without polling. The socket is best effort, and the SDK treats it that way:

  • while the socket is up it only runs a slow safety check, to recover a lost event;
  • if the socket drops or the channel is denied, it switches to polling with growing intervals;
  • once subscribed it reads the status again (the final event may have arrived earlier);
  • at the end it closes the channel; channels are shared between listeners.
js
const stop = dk.scanner.watch(id, (e) => console.log(e.status, e.percentage)); // listen only
dk.realtime.user(userId, { onToast: (t) => notify(t.message) });              // personal events
dk.realtime.onStateChange((state) => console.log('socket', state));
dk.close();                                                                     // when done

To open the socket when your app starts (the first search is faster): await dk.realtime.connect().

Census and monitoring ​

js
const { scanner_request_id: parent } = await dk.census.create();             // or { searchMode: 'MULTI_ADDRESS' }
const candidates = await dk.census.findAddresses({ indirizzo, comune, provincia });
await dk.census.addAddress(parent, { indirizzo, comune, provincia, address_value, numero_civico });
const census = await dk.census.wait(parent);

await dk.monitorings.fromCatasto({ comune, provincia, foglio, particella, webhook_url });
const list = await dk.monitorings.list({ type: 'IMMOBILE' });
const { wallet } = await dk.account.wallet();

Each user can run only one census at a time (CensusInProgressError).

Errors ​

Every error extends DokicasaError and has a code; API errors also have status and body. Handle them with instanceof:

ClassWhenUseful data
InsufficientFundsErrorNot enough credit or balance (AMOUNT_NOT_ENOUGH)missingAmount, checkoutLink
ValidationErrorInvalid data (422), invalid tax codefields, isDuplicate
CensusInProgressErrorA census is already running (PENDING_CENSIMENTO)
ServiceUnavailableErrorSister down, in maintenance or overloaded
RateLimitErrorToo many requests (429)retryAfterSeconds
PartnerPricingRequiredErrorSearch type not enabled on your accountscannerType
AuthenticationError / PermissionError / NotFoundError401 / 403 / 404
ScanFailedErrorSearch ended in ERROR or CANCELLEDrequest
TimeoutError / AbortError / NetworkErrorTime out, cancelled, network down
js
try {
  await dk.scanner.run('visura-catasto', data);
} catch (e) {
  if (e instanceof InsufficientFundsError) return openCheckout(e.checkoutLink);
  if (e instanceof ValidationError && e.isDuplicate) return notice('Search already running');
  if (e instanceof ServiceUnavailableError) return notice('Land registry temporarily unavailable');
  throw e;
}

Duplicates

The API rejects an identical search made a few seconds later (one hour for documents): ValidationError with isDuplicate === true. Don't show it as an error.

Waiting, timeouts and cancellation ​

js
const controller = new AbortController();
const r = await dk.scanner.run('ispezione-tax-data', data, {
  signal: controller.signal,     // cancels calls and wait
  timeoutMs: 10 * 60_000,        // max wait (default 15 minutes)
  maxConsecutiveErrors: 5,       // network errors tolerated while waiting
  throwOnFailure: false,         // returns the request even if it ended in ERROR
});

Cancelling the wait does not stop the search: it goes on server side and you can resume with dk.scanner.wait(id).

SSO partners: acting on behalf of a user ​

If your users enter Dokicasa with direct access (SSO), you can call on behalf of one of them with your own token: searches, credits and real-time channels will be theirs.

js
const agent = dk.as({ email: 'agent@example.com' });   // or dk.as('<slug>:<external id>')
await agent.account.wallet();
await agent.scanner.run('catasto', data);

The SDK sends the X-Dokicasa-User header (email:<email> or <partner slug>:<external id>). It only works for users linked to your partner account; for anyone else the answer is 403 ACTING_USER_FORBIDDEN, with the same message for users that do not exist.

Enabled on request

Dokicasa has to enable the header on your partner account: ask your contact.

Webhook ​

To avoid waiting, pass webhook to the search. Verify the signature on the raw body, before JSON.parse (signature details):

js
import { parseWebhook } from '@dokicasa/sdk';

app.post('/webhook/dokicasa', express.raw({ type: '*/*' }), async (req, res) => {
  try {
    const event = await parseWebhook({ body: req.body, signature: req.get('Signature'), secret: process.env.DOKICASA_TOKEN });
    res.sendStatus(200);
  } catch {
    res.sendStatus(401);
  }
});

Demo, examples and tests ​

The npm package contains the whole project: sources, tests, demos and examples, in node_modules/@dokicasa/sdk/. The demos start with one command, no cloning:

bash
DOKICASA_TOKEN=<sandbox token> npx -p @dokicasa/sdk dokicasa-sdk-demo
PageWhat it does
Playground (localhost:5174)any search, showing where each update came from (socket or polling), multi-step choices, PDFs and explained errors
Live examples (/esempi)12 examples (visura, tax code, census, monitoring, errors, webhook, SSO partners, prices, cancellation...) with the code alongside
Vue (/vue) and React (/react)the same component with useScanner(): search, progress bar, cancel, resume by id, PDF

The same 12 examples also run in Node (examples/), plus 132 unit tests and an end-to-end suite against the sandbox: DOKICASA_E2E_TOKEN=<token> npm run test:e2e.

Security ​

  • The API token is like a password: never put it in code or in a public frontend. In the browser use the single user's token, never the partner's.
  • Server-side calls must come from an origin enabled on your account (ORIGIN_NOT_ALLOWED otherwise).