Skip to content

Guides

Build a screening pipeline

Sync jobs and applicants from an ATS, score them, re-rank with the recruiter’s priorities and search the talent pool, with your own ids.

An ATS integration keeps HireLayer in step with its own ids: one workspace per customer company, each job stored under its ATS id, each applicant’s resume under its application id. Then a recruiter reads a ranking that costs nothing to reload, and can widen it to the whole talent pool.

  1. 1

    Store the job

    PUT /jobs/{job_id} with the job description stores it under your id and extracts its criteria, for free. When the ad changes, send it again with recompute_criteria: true to extract its criteria again: a criterion that keeps its label and threshold keeps its results, the others are evaluated again (1 credit per stored score). A field left out of a PUT keeps its stored value: send only what changed.

  2. 2

    Score each applicant

    POST /resumes/score with {"job": {"job_id": …}} and the resumes, each with your application_id: files are parsed and stored, then scored. 1 credit per resume scored, +1 per file; a pair already scored is free. Score new applicants as they arrive, or in batches of up to 10 files for a synchronous answer.

  3. 3

    Read the ranking

    GET /jobs/{job_id}/scores returns every score of the job, best first. Pass the recruiter’s priorities for one view, weights[crit_3]=0 or requirements[crit_1]=required: nothing is evaluated again, so it is free. precise_ranking=true compares the 10 best against each other and adds a ranking_reason, for 1 credit per read.

  4. 4

    Search the talent pool

    POST /resumes/search with the job_id finds the closest resumes of the whole workspace, including past applicants, for 1 credit. Score the ones not already_scored by their application_id. For the opposite direction, POST /jobs/search finds the open jobs closest to a resume.

# screening.py: store a job from your ATS, score its applicants, re-rank, then search the talent pool.
from hirelayer import call, read_file

WORKSPACE = "acme"  # one workspace per customer company
JOB_ID = "req-2026-114"  # your ATS ids, used as is

with open("job.txt", encoding="utf-8") as file:
    job_text = file.read()

# 1. Store the job under its ATS id: its criteria are extracted once (free).
job = call("PUT", f"/jobs/{JOB_ID}", body={"text": job_text, "status": "open"}, workspace=WORKSPACE)
print([(c["criterion_id"], c["label"], c["weight"]) for c in job["criteria"]])

# 2. Score the applicants, their files stored under their ATS ids (up to 10 files per synchronous call).
applicants = {"app-1": "alex.pdf", "app-2": "sam.pdf", "app-3": "charlie.pdf"}
files = {f"cv{i}": read_file(path) for i, path in enumerate(applicants.values(), start=1)}
resumes = [{"file": f"cv{i}", "application_id": app} for i, app in enumerate(applicants, start=1)]
call("POST", "/resumes/score", body={"job": {"job_id": JOB_ID}, "resumes": resumes}, files=files, workspace=WORKSPACE)

# 3. Read the ranking with the recruiter's priorities: crit_3 off for this view, free.
ranking = call("GET", f"/jobs/{JOB_ID}/scores?weights[crit_3]=0&precise_ranking=true", workspace=WORKSPACE)
for score in ranking["data"]:
    print(score["rank"], score["application_id"], score["score"], score["verdict"], score["summary"])

# 4. Search the whole talent pool for this job, then score the closest resumes not scored yet.
closest = call("POST", "/resumes/search", body={"job_id": JOB_ID, "limit": 20}, workspace=WORKSPACE)["results"]
new = [{"application_id": r["application_id"]} for r in closest if not r["already_scored"]]
if new:
    call("POST", "/resumes/score", body={"job": {"job_id": JOB_ID}, "resumes": new}, workspace=WORKSPACE)
// screening.mts: store a job from your ATS, score its applicants, re-rank, then search the talent pool.
// Run: npx tsx screening.mts
import { readFile } from 'node:fs/promises'
import { callHireLayer, readPart } from './hirelayer.mts'

type Criterion = { criterion_id: string; label: string; weight: number }
type Job = { job_id: string; criteria: Criterion[] }
type Score = {
  rank: number
  application_id: string
  score: number | null
  verdict: string | null
  summary: string | null
}

const workspace = 'acme' // one workspace per customer company
const jobId = 'req-2026-114' // your ATS ids, used as is
const jobText = await readFile('job.txt', 'utf8')

// 1. Store the job under its ATS id: its criteria are extracted once (free).
const job = await callHireLayer<Job>(`/jobs/${jobId}`, {
  method: 'PUT',
  body: { text: jobText, status: 'open' },
  workspace,
})
console.log(job.criteria.map((c) => [c.criterion_id, c.label, c.weight]))

// 2. Score the applicants, their files stored under their ATS ids (up to 10 files per synchronous call).
const applicants = { 'app-1': 'alex.pdf', 'app-2': 'sam.pdf', 'app-3': 'charlie.pdf' }
const entries = Object.entries(applicants)
const files = Object.fromEntries(
  await Promise.all(entries.map(async ([, path], i) => [`cv${i + 1}`, await readPart(path)]))
)
await callHireLayer('/resumes/score', {
  body: {
    job: { job_id: jobId },
    resumes: entries.map(([id], i) => ({ file: `cv${i + 1}`, application_id: id })),
  },
  files,
  workspace,
})

// 3. Read the ranking with the recruiter's priorities: crit_3 off for this view, free.
const ranking = await callHireLayer<{ data: Score[] }>(
  `/jobs/${jobId}/scores?weights[crit_3]=0&precise_ranking=true`,
  { workspace }
)
for (const score of ranking.data) {
  console.log(score.rank, score.application_id, score.score, score.verdict, score.summary)
}

// 4. Search the whole talent pool for this job, then score the closest resumes not scored yet.
const { results } = await callHireLayer<{
  results: Array<{ application_id: string; already_scored: boolean }>
}>('/resumes/search', { body: { job_id: jobId, limit: 20 }, workspace })
const fresh = results.filter((r) => !r.already_scored)
if (fresh.length) {
  await callHireLayer('/resumes/score', {
    body: {
      job: { job_id: jobId },
      resumes: fresh.map((r) => ({ application_id: r.application_id })),
    },
    workspace,
  })
}
# hirelayer.py: minimal client with retries. Requires: pip install requests
import json
import os
import random
import time

import requests

API_BASE = "https://hirelayer.co/api/v4"
RETRYABLE = {429, 502, 503, 504}


class HireLayerError(Exception):
    def __init__(self, status, code, message, param=None, request_id=None):
        super().__init__(f"HireLayer {status} {code}: {message} (request_id {request_id})")
        self.status = status
        self.code = code
        self.param = param
        self.request_id = request_id


def _delay(attempt, retry_after):
    if retry_after and retry_after.isdigit():
        return int(retry_after)
    return min(30, 2**attempt) + random.random()


def call(method, path, *, body=None, files=None, workspace=None, timeout=150, max_retries=3):
    """Call HireLayer. Retries 429, 502, 503, 504 and connection failures, raises HireLayerError otherwise."""
    headers = {"X-API-Key": os.environ["HIRELAYER_API_KEY"]}
    if workspace:
        headers["HireLayer-Workspace"] = workspace
    # With files, the JSON goes in the "request" part.
    data = {"request": json.dumps(body)} if files and body is not None else None
    for attempt in range(max_retries + 1):
        try:
            response = requests.request(
                method,
                API_BASE + path,
                headers=headers,
                json=None if files else body,
                data=data,
                files=files,
                timeout=timeout,
            )
        except requests.ConnectionError:
            if attempt == max_retries:
                raise
            time.sleep(_delay(attempt, None))
            continue

        if response.status_code == 204:
            return None
        if response.ok:
            return response.json()
        if response.status_code in RETRYABLE and attempt < max_retries:
            time.sleep(_delay(attempt, response.headers.get("Retry-After")))
            continue
        try:
            error = response.json()["error"]
        except (ValueError, KeyError, TypeError):
            error = {"code": None, "message": response.reason}
        raise HireLayerError(
            response.status_code,
            error.get("code"),
            error.get("message"),
            error.get("param"),
            response.headers.get("HireLayer-Request-Id"),
        )


def read_file(path):
    """A multipart file part, as bytes so it can be sent again on retry."""
    with open(path, "rb") as file:
        return (os.path.basename(path), file.read())


def score_files(job_path, resume_paths, precise_ranking=False, workspace=None):
    """Score resume files against a job file: 1 credit per resume, +1 per file parsed."""
    files = {"job": read_file(job_path)}
    resumes = []
    for index, path in enumerate(resume_paths, start=1):
        files[f"cv{index}"] = read_file(path)
        resumes.append({"file": f"cv{index}", "reference": os.path.basename(path)})
    body = {"job": {"file": "job"}, "resumes": resumes, "precise_ranking": precise_ranking}
    return call("POST", "/resumes/score", body=body, files=files, workspace=workspace)
// hirelayer.mts: minimal client with retries. Node.js 18+, run with tsx.
import { readFile } from 'node:fs/promises'
import { basename } from 'node:path'

const API_BASE = 'https://hirelayer.co/api/v4'
const RETRYABLE = new Set([429, 502, 503, 504])

export class HireLayerError extends Error {
  constructor(
    readonly status: number,
    readonly code: string | undefined,
    message: string,
    readonly param?: string,
    /** Quote it to support. */
    readonly requestId?: string | null
  ) {
    super(`HireLayer ${status} ${code}: ${message} (request_id ${requestId})`)
  }
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function retryDelay(attempt: number, retryAfter: string | null) {
  const seconds = Number(retryAfter)
  if (retryAfter && Number.isInteger(seconds)) return seconds * 1000
  return Math.min(30_000, 1000 * 2 ** attempt) + Math.random() * 1000
}

type CallOptions = {
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
  /** The JSON body, or the `request` part when `files` are sent. */
  body?: unknown
  /** Multipart file parts, by part name. */
  files?: Record<string, { name: string; bytes: Uint8Array }>
  workspace?: string
  timeoutMs?: number
}

/** Calls HireLayer. Retries 429, 502, 503, 504 and connection failures, throws HireLayerError otherwise. */
export async function callHireLayer<T>(
  path: string,
  options: CallOptions = {},
  maxRetries = 3
): Promise<T> {
  const headers: Record<string, string> = {
    'X-API-Key': process.env.HIRELAYER_API_KEY!,
  }
  if (options.workspace) headers['HireLayer-Workspace'] = options.workspace
  if (options.body !== undefined && !options.files) {
    headers['Content-Type'] = 'application/json'
  }

  for (let attempt = 0; ; attempt++) {
    // A FormData is consumed by a request: build it again on every attempt.
    let body: string | FormData | undefined
    if (options.files) {
      body = new FormData()
      if (options.body !== undefined) {
        body.append('request', JSON.stringify(options.body))
      }
      for (const [part, file] of Object.entries(options.files)) {
        body.append(part, new Blob([file.bytes]), file.name)
      }
    } else if (options.body !== undefined) {
      body = JSON.stringify(options.body)
    }

    let response: Response
    try {
      response = await fetch(API_BASE + path, {
        method: options.method ?? (body === undefined ? 'GET' : 'POST'),
        headers,
        body,
        signal: AbortSignal.timeout(options.timeoutMs ?? 150_000),
      })
    } catch (error) {
      // fetch rejects with a TypeError when the connection fails.
      if (!(error instanceof TypeError) || attempt >= maxRetries) throw error
      await sleep(retryDelay(attempt, null))
      continue
    }
    if (response.status === 204) return undefined as T
    if (response.ok) return (await response.json()) as T
    if (RETRYABLE.has(response.status) && attempt < maxRetries) {
      await sleep(retryDelay(attempt, response.headers.get('Retry-After')))
      continue
    }
    const payload = await response.json().catch(() => ({}))
    const error = payload.error ?? {}
    throw new HireLayerError(
      response.status,
      error.code,
      error.message ?? response.statusText,
      error.param,
      response.headers.get('HireLayer-Request-Id')
    )
  }
}

export async function readPart(path: string) {
  return { name: basename(path), bytes: await readFile(path) }
}
  • A candidate sends a new resume: send it with the same application_id. Its scores become stale and are evaluated again the next time the resume is scored.
  • A job is filled: PUT /jobs/{job_id} with {"status": "closed"} keeps its scores and takes it out of Job Recommendations.
  • A candidate asks for erasure: DELETE /resumes/{application_id} removes the resume and its scores. A customer leaves: DELETE /workspaces/{workspace_id} removes everything it holds.
  • More than 10 files at once: parse them with POST /resumes/parse (or send a webhook_url), then score them by id.