Get started
Errors and retries
The error format of the HireLayer API, every error code, and when to retry a call.
Successful calls return 2xx. Every error returns a non-2xx status and the same JSON body. Branch on error.code, never on error.message: codes are stable, messages are for humans and may change.
{
"error": {
"code": "invalid_request",
"message": "job.criteria[0].weight must be 0, 1, 2 or 3.",
"param": "job.criteria[0].weight",
"doc_url": "https://hirelayer.co/api-docs/errors#invalid_request"
},
"request_id": "6f1c2a4e-1d2b-4c3a-9e8f-0a1b2c3d4e5f"
}paramnames the input at fault: its full path from the root of the body (job.criteria[0].weight,resumes[2].file), or the path parameter, query parameter or header (job_id,limit,HireLayer-Workspace). Errors about the whole call (the key, credits, an unreadable body, an unknown endpoint) have none.request_ididentifies the call, and every answer carries it in theHireLayer-Request-Idheader too, successes included: quote it when contacting support.doc_urllinks to the code below. Each endpoint’s reference lists the errors it answers, with the message of each case.- In a scoring call, a resume that fails (unreadable file, unknown
application_id) does not fail the call: it comes last withevaluation_status: "failed"and its ownerror, unbilled.
- A message is one or two English sentences: what is wrong, starting with the input at fault, then what to do. A size limit is always cited:
text must be 5,000 characters or less. - A refusal before any work ends with
Nothing was processed or billed.; an unreadable resume file withNothing was billed. - The same situation answers the same status and code on every endpoint: a content over its size limit is always
413 payload_too_large, an unknown id always404 not_foundwith the field inparam, a method a path does not take405 method_not_allowedwith anAllowheader. - Messages may be reworded; codes do not change. Branch on
error.code.
- Retry
429after theRetry-Afterheader, and502,503and504or connection failures at most 3 times with exponential backoff and jitter (about 1 s, 2 s, 4 s). After a504, a change may still have been applied: read it before sending the call again. - Never retry another
4xxunchanged.403 insufficient_creditssucceeds once credits are added. - Failed work is not billed. Keep a client timeout of 150 seconds on the products: a call your client abandons can still complete and be billed.
- Writes to your own ids (
PUT /jobs/{job_id},PUT /resumes/{application_id}) can be sent again safely, and a pair already scored is not billed again.
# 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) }
}
`400`. The request is invalid: a missing or unknown field, a wrong type, a value out of its range, malformed JSON or multipart, an id that is malformed or names an endpoint (score, search…). param names the field at fault. Fix the request. Do not retry it unchanged.
`400`. The call needs storage while it runs without it: a search, a stored job_id or application_id read with do_not_store_data=true, or, in a workspace set to run without storage, a write that would store something in it (PUT /resumes/{application_id}, PUT /jobs/{job_id}, POST /jobs/{job_id}/criteria, PATCH /jobs/{job_id}/criteria/{criterion_id}). Send the content instead of its id, or call without do_not_store_data. A workspace set with do_not_store_data: true refuses these calls whatever they send: use another workspace, or lift the setting with PUT /workspaces/{workspace_id}.
`401`. The X-API-Key header is missing, or the key came another way: Authorization: Bearer or the URL, which are not accepted. Send the key in the X-API-Key header.
`401`. The key is malformed, unknown or revoked. Check the key in the dashboard.
`403`. The account has fewer credits than the call needs. Nothing was processed or billed. Add credits, then retry.
`403`. do_not_store_data=true below the Enterprise plan. Nothing was processed or billed. Send the call without it, or move to the Enterprise plan.
`404`. No job, resume, criterion, score, workspace or Scorer call under this id in the workspace, param naming the field that carries it; or no such endpoint, without param. Check the path, the ids and the HireLayer-Workspace header.
`405`. The path exists, but not with this method, such as GET /resumes/score. The Allow header lists the methods it takes. Use a method of the Allow header.
`413`. A content is over its size limit: a file over 4.5 MB, the files of a call over 50 MB, a parsed resume JSON over 1 MB, a job or resume text over 50,000 characters, a Skills Normalizer text over 5,000 characters, or a body over 10 MB. param names the input, and the message the limit. Send a smaller input, or parse the files first and score them by id.
`422`. The resume file cannot be read. Nothing was billed. In a scoring call, only that resume fails. Do not retry the same file.
`422`. The job file cannot be read. Nothing was billed. Send the job as text, or another file.
`429`. Too many files are being parsed at once for the account. Wait for Retry-After seconds, then retry.
`502`. The analysis could not be completed after several attempts. Nothing was billed. A failed score also carries this code in its error. Retry with backoff.
`500` `502` `503` `504`. An unexpected failure (500), the service out of reach (502), a dependency briefly unavailable (503), or no answer in time (504). Retry with backoff; honour Retry-After. After a 504, a change may still have been applied: read it before sending the call again. If it persists, contact support with the request_id.
The legacy parsers keep their own error shape, {"error": "…", "code": "…"}, with these exact messages:
POST/api/v3/parser24 errors›
- 400
UNSUPPORTED_OUTPUT_FORMATUnsupported output_format. Use one of: hirelayer, hrflowFix, then retry
- 400
INVALID_MULTIPART_BODYThe request body is not valid multipart/form-data. Check the boundary and the Content-Disposition header of each part.Do not retry
- 400Missing required file field
Do not retry
- 400Prefer: respond-async requires a webhook_url field with an HTTPS URL
Do not retry
- 400application_id must be a string when provided
Do not retry
- 400application_id must contain letters, digits and . _ : ~ -, up to 200 characters
Do not retry
- 400HireLayer-Workspace must contain letters, digits and . _ : ~ -, up to 200 characters
Do not retry
- 400
INVALID_FILEThe uploaded file is empty or invalid. Please check the file and try again.Do not retry
- 401Missing API Key
Do not retry
- 401Invalid API Key
Do not retry
- 403Insufficient credits available
Fix, then retry
- 403
ENTERPRISE_PLAN_REQUIREDdo_not_store_data=true is reserved for the Enterprise plan. Send the request without it, or with do_not_store_data=false.Fix, then retry
- 413The uploaded file is too large to process. Please upload a smaller file.
Do not retry
- 413The request body is larger than the 10 MB limit. Please upload a smaller file.
Do not retry
- 415Content-Type must be multipart/form-data
Do not retry
- 422
DOCUMENT_NOT_A_RESUMEThis document does not appear to be a CV or resume. Please upload a CV or resume and try again.Do not retry
- 422
DOCUMENT_TEXT_EMPTYThe text could not be extracted from this document. Please verify that the file is readable and contains selectable text.Do not retry
- 422
DOCUMENT_UNREADABLEThe document could not be read. Please upload a valid, readable file.Do not retry
- 422
DOCUMENT_TOO_LARGEThis document contains too much text to process. Please try a shorter or simpler version.Do not retry
- 500Internal Server Error
Retry with backoff
- 502
PARSER_UNAVAILABLEAn error occurred while processing the document or extracting its text. Please try again later.Retry with backoff
- 503
PARSER_UNAVAILABLEAn error occurred while processing the document or extracting its text. Please try again later.Retry with backoff
- 503Credit service temporarily unavailable
Retry with backoff
- 504
PARSER_UNAVAILABLEAn error occurred while processing the document or extracting its text. Please try again later.Retry with backoff
POST/api/v2/parser9 errors›
- 400
INVALID_MULTIPART_BODYThe request body is not valid multipart/form-data. Check the boundary and the Content-Disposition header of each part.Do not retry
- 400An error occurred while processing the document or extracting its text. Please try again later.
Do not retry
- 401Missing API Key
Do not retry
- 401Invalid API Key
Do not retry
- 403Insufficient credits available
Fix, then retry
- 413The request body is larger than the 10 MB limit. Please upload a smaller file.
Do not retry
- 415Content-Type must be multipart/form-data
Do not retry
- 500Internal Server Error
Retry with backoff
- 503Credit service temporarily unavailable
Retry with backoff