Node.js

Node.js examples

Six examples ready to copy, from the first call to error handling, with the hosted sample certificate (fictitious data).

Before you start

Three steps, once.

  1. Create an API key

    In the panel, under API Keys.

  2. Put the key in the environment

    In the DOCSOCR_API_KEY variable, which the examples read. The prices example needs no key.

  3. Save and run

    Save each example under the name shown above its code. Its first lines say what it needs to run.

Your first call

Sends the hosted sample certificate (fictitious data) and prints the JSON answer.

first-call.mjs
// Your first call: extract the hosted sample certificate (fictitious data).
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'url',
    imageUrl: 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
    requestId: randomUUID(), // one id per document
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)

A local file in base64

Reads an image from your machine and sends it in base64, with no public URL needed.

local-file.mjs
// Extract a certificate from a local file, sent in base64.
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'

const imageBase64 = (await readFile('certificate.jpg')).toString('base64')

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'base64',
    imageBase64,
    requestId: randomUUID(), // one id per document
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)

An image outside our standard

With resizeImage: true, an image outside our size standard is resized on our side for 1 credit more, instead of refused.

resize.mjs
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'url',
    imageUrl: 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
    requestId: randomUUID(), // one id per document
    resizeImage: true,
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)
console.log('resized:', answer.imageResized ?? false, 'credits:', answer.creditsCharged)

The fast engine

Asks for the fast engine: it is tried first, at its own price, and the standard engines answer when it cannot. The answer names the engine that answered and what it cost.

fast.mjs
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'

const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    imageType: 'url',
    imageUrl: 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
    requestId: randomUUID(), // one id per document
    engine: 'fast',
  }),
  signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
  console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
  process.exit(1)
}
console.log('engine:', answer.engine, 'credits:', answer.creditsCharged)

Errors and retries

Handles every answer and retries with the same requestId: for 15 minutes, a repeat of a finished request gets the same answer at no charge, and a repeat of one still running gets a 409, to wait.

errors.mjs
// Extract a certificate, handling every answer, with retries that never charge twice.
// Each retry sends the same requestId: a repeat of a finished request gets its
// kept answer at no charge, and a repeat of one still running is told to wait (409).
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'
import { setTimeout as sleep } from 'node:timers/promises'

const ENDPOINT = 'https://api.docsocr.com/api/v1/documents/birth-certificate'
// No engine could answer: nothing was charged, and a retry may succeed
const RETRY_LATER = new Set(['EXTRACTION_BUSY', 'EXTRACTION_TIMEOUT', 'EXTRACTION_UNAVAILABLE'])
// Still in progress, too many requests, the service restarting
const RETRY_STATUS = new Set([409, 429, 502, 503, 504])

async function extract(imageUrl, attempts = 5) {
  const requestId = randomUUID() // one id per document, the same on every retry
  for (let attempt = 0; attempt < attempts; attempt++) {
    const backoff = 2 ** attempt // seconds: 1, 2, 4, 8
    let response
    try {
      response = await fetch(ENDPOINT, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ imageType: 'url', imageUrl, requestId }),
        signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
      })
    } catch {
      await sleep(backoff * 1000) // a timeout or a dropped connection
      continue
    }
    const isJson = (response.headers.get('content-type') ?? '').startsWith('application/json')
    const answer = isJson ? await response.json() : {}
    if (response.status === 201 && answer.success) return answer
    // Wait as long as the answer asks (retryAfter); a limit that resets
    // later, such as a daily quota, is not worth waiting for
    const wait = answer.retryAfter || backoff
    const retry = RETRY_LATER.has(answer.errorCode) || RETRY_STATUS.has(response.status)
    if (retry && wait <= 60) {
      await sleep(wait * 1000)
      continue
    }
    // 400 the body, 401 the key, 402 NOT_ENOUGH_CREDITS, 422 the image
    // (its errorCode says what to fix), DOCUMENT_NOT_RECOGNIZED: fix it, don't retry
    throw new Error(`${response.status} ${answer.errorCode ?? ''} ${answer.message ?? answer.error}`)
  }
  throw new Error('No answer after retries: try again later')
}

try {
  const answer = await extract('https://docsocr.com/samples/certidao-nascimento-exemplo.jpg')
  console.log(answer.data.dados_pessoais.nome_completo, 'credits:', answer.creditsCharged)
} catch (error) {
  console.error(error.message)
  process.exit(1)
}

Prices

Reads the price of an extraction in credits, per engine and for resizeImage. No key needed.

prices.mjs
// The price of an extraction, in credits, per engine and for resizeImage.
// A public endpoint: no key needed. Needs Node.js 18+.
const response = await fetch('https://api.docsocr.com/api/v1/documents/prices', {
  signal: AbortSignal.timeout(30_000),
})
if (!response.ok) {
  console.error(response.status)
  process.exit(1)
}
for (const [name, credits] of Object.entries(await response.json())) {
  console.log(`${name}: ${credits} credit(s)`)
}

Ready to start?

Create your account, get free credits and run the first example with your key.