Skip to content

How to Build an AI Resume Screener in Python: Parse, Score and Explain

How AI resume screening works, and a Python program that screens a folder of CVs against a job: criteria, per-requirement evidence, scores and a shortlist.

Updated · 10 minutes read

Cover reading “Build an AI resume screener” with a candidate icon and a chart icon

AI resume screening reads every application for a job and tells a recruiter which ones meet the requirements, and why. Done well, it gives each CV the same careful read as the first ten in the inbox. Done badly, it is a keyword filter with a confident score attached. This guide explains how AI resume screening works, then walks through a Python program that screens a folder of resumes against one job description with the HireLayer APIs, from the parsed CV to an explained shortlist.

How AI resume screening works

Most screening tools, whatever they call themselves, chain the same four steps. Knowing them helps you judge a vendor or build your own feature.

StepWhat it producesHireLayer endpoint
1. Parse each resumeA structured record plus the full text of the CV, including scansPOST /api/v4/resumes/parse
2. Turn the job into criteriaWeighted requirements, each required, preferred or a bonusPOST /api/v4/jobs/extract-criteria
3. Evaluate each candidateA status and the evidence for every criterion, a 0–1 score and a verdictPOST /api/v4/resumes/score
4. Order the shortlistThe 10 best candidates ranked side by side, each with a reasonPOST /api/v4/resumes/score with precise_ranking

The order matters. Criteria are written once per job and reviewed by a person before any candidate is scored, so every application is judged against the same list. The decision to advance or reject someone stays outside the API, in your product, with a name next to it.

Keyword filters versus criterion-based screening

A keyword filter asks whether a word appears in the CV. “Led a support team of six” doesn't contain “people management”, so the filter drops a candidate a recruiter would have kept. It also rewards CVs stuffed with the job ad’s vocabulary, wich is exactly what job seekers are told to do.

Criterion-based screening asks a different question for each requirement: does the resume show it, partly show it, say nothing, or contradict it? TheHireLayer Resume Scorer returns one of four statuses per criterion, with the evidence quoted from the CV:

  • met: clearly met.
  • partial: partly met, for example below the threshold the job asks for.
  • unknown: the resume says nothing about something resumes often leave out, such as availability or mobility.
  • missing: not met, or a skill, degree or experience the resume does not show.

The difference between unknown and missing is the one that matters most in practice. A CV that never lists a required skill is read as lacking it, while a CV that says nothing about availability is simply silent, and your screen shouldn't treat them the same way.

Build the screener in Python

The program below reads a job description from job.txt, screens every resume in an applications folder and writes the results to screening.json for a recruiter to review. You need Python 3.9 or later, pip install requests and an API key in the HIRELAYER_API_KEY environment variable. Keep the key on the server; it never belongs in browser code.

The client

Save this as hirelayer.py. It sends the key in the X-API-Key header, retries busy or unavailable answers and dropped connections with backoff, and raises an error that carries the HTTP status and the API's error code. The screening pipeline guide covers the same calls.

# hirelayer.py: minimal client for the HireLayer API, with retries. Requires: pip install requests
import mimetypes
import os
import random
import time

import requests

API_BASE = "https://hirelayer.co/api/v4"


class HireLayerError(Exception):
    def __init__(self, status, code, message, param=None):
        super().__init__(f"HireLayer {status} {code}: {message}")
        self.status = status
        self.code = code  # such as "resume_unreadable": branch on it, never on the message
        self.message = message
        self.param = param


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, *, json=None, files=None, data=None, timeout=150, max_retries=3):
    """Call HireLayer. Retries 429, 502, 503 and connection failures, raises HireLayerError otherwise."""
    headers = {"X-API-Key": os.environ["HIRELAYER_API_KEY"]}
    for attempt in range(max_retries + 1):
        try:
            response = requests.request(
                method,
                API_BASE + path,
                headers=headers,
                json=json,
                files=files,
                data=data,
                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 (429, 502, 503) and attempt < max_retries:
            time.sleep(_delay(attempt, response.headers.get("Retry-After")))
            continue

        # Errors are {"error": {"code", "message", "param", "doc_url"}}.
        try:
            error = response.json().get("error")
        except ValueError:
            error = None
        if not isinstance(error, dict):  # not a HireLayer answer, e.g. a proxy page
            error = {"message": response.reason}
        raise HireLayerError(
            response.status_code, error.get("code"), error.get("message"), error.get("param")
        )


def parse_resume(path, application_id=None):
    content_type = mimetypes.guess_type(path)[0] or "application/octet-stream"
    with open(path, "rb") as file:
        content = file.read()  # bytes can be re-sent on retry
    return call(
        "POST",
        "/resumes/parse",
        files={"file": (os.path.basename(path), content, content_type)},
        data={"application_id": application_id} if application_id else None,
    )

The screening program

Save this as screen.py and run python screen.py. The first run extracts the criteria and stops, so a recruiter can edit criteria.json before anything is scored: drop a requirement the hiring manager doesn't really care about, lower a weight, or make a required criterion preferred. The second run does the screening.

# screen.py: screen every resume in ./applications against one job.
import json
import re
from pathlib import Path

from hirelayer import HireLayerError, call, parse_resume

BATCH = 50  # resumes per Resume Scorer call that answers right away
RESUME_EXTENSIONS = {".pdf", ".doc", ".docx", ".odt", ".ppt", ".pptx", ".odp", ".xls", ".rtf", ".txt", ".html", ".htm", ".xhtml", ".md", ".markdown", ".jpg", ".jpeg", ".png", ".bmp"}

job_text = Path("job.txt").read_text(encoding="utf-8")

# 1. Turn the job into criteria once (free), then let a recruiter review them.
criteria_file = Path("criteria.json")
if not criteria_file.exists():
    extracted = call("POST", "/jobs/extract-criteria", json={"text": job_text})
    criteria_file.write_text(
        json.dumps(extracted["criteria"], ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    raise SystemExit("Review criteria.json (labels, weights, requirement), then run again.")
criteria = json.loads(criteria_file.read_text(encoding="utf-8"))

# 2. Parse each application once. HireLayer stores it under your application_id.
files = {}  # application_id -> file name
results = []
for path in sorted(Path("applications").iterdir()):
    if path.suffix.lower() not in RESUME_EXTENSIONS:
        continue
    # application_id takes letters, digits and . _ : ~ - only, up to 200 characters,
    # and keeps cv.pdf and cv.docx apart.
    application_id = re.sub(r"[^A-Za-z0-9._:~-]", "_", path.name)[:200]
    try:
        parse_resume(str(path), application_id=application_id)
    except HireLayerError as error:
        # Not a resume, unreadable, empty or too large: final for this file, a
        # person checks it. Other errors stop the run.
        if error.code in ("resume_unreadable", "payload_too_large"):
            results.append({"id": path.name, "status": "manual_review", "reason": error.message})
            continue
        raise
    files[application_id] = path.name

# 3. Score the stored resumes against the reviewed criteria, 50 per call.
job = {"text": job_text, "criteria": criteria}
ids = list(files)
for start in range(0, len(ids), BATCH):
    answer = call(
        "POST",
        "/resumes/score",
        json={"job": job, "resumes": [{"application_id": i} for i in ids[start:start + BATCH]]},
    )
    job = {"job_id": answer["job"]["job_id"]}  # next calls reuse the stored job and criteria
    for item in answer["scores"]:
        name = files[item["application_id"]]
        if item["evaluation_status"] != "completed":
            results.append({"id": name, "status": "manual_review", "reason": item["error"]["message"]})
            continue
        results.append({
            "id": name,
            "application_id": item["application_id"],
            "status": "flagged" if item["required_missing"] else "scored",
            "score": item["score"],
            "verdict": item["verdict"],
            "summary": item["summary"],
            "required_missing": [c["label"] for c in item["required_missing"]],
            "to_verify": [c["label"] for c in item["to_verify"]],
            "criteria": item["criteria"],
        })

# 4. Order the scored pool. Every score uses the same criteria, so they compare.
scored = sorted(
    (r for r in results if r["status"] == "scored"), key=lambda r: r["score"], reverse=True
)

# 5. Optional: re-rank the top 10 side by side, with a reason for each place.
# These pairs are already scored: the call costs 1 credit, for the ranking.
if len(scored) > 1:
    ranked = call(
        "POST",
        "/resumes/score",
        json={
            "job": job,
            "resumes": [{"application_id": r["application_id"]} for r in scored[:10]],
            "precise_ranking": True,
        },
    )["scores"]
    for item in ranked:
        print(item["rank"], files[item["application_id"]], item["score"], item["ranking_reason"])

# 6. Save everything for the recruiter's review screen. Nobody is rejected here.
Path("screening.json").write_text(
    json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8"
)

Each application costs two credits, one to parse it and one to score it. Extracting the criteria is free, and the optional ranking costs one credit per call: its pairs are already scored, so nothing else is billed. Parsing takes about 25 to 35 seconds per file, so for more than a handful of CVs run the loop in a background worker and process a few files in parallel. The bulk parsing guide covers queues, retries and duplicates.

What one evaluated criterion looks like

Every criterion you send comes back in the same order with its status, evidence and explanation. Explanations and summaries follow the job's language (English, French, German, Spanish or Portuguese; English for any other), and the evidence quotes the resume in its own language. This one comes from an English job description:

{
  "criterion_id": "crit_2",
  "label": "Backend development with Node.js / TypeScript",
  "requirement": "preferred",
  "weight": 3,
  "status": "partial",
  "score": 0.67,
  "gap": "below_threshold",
  "confidence": "medium",
  "evidence": "API stack (serverless AWS): API Gateway, Lambda, S3, DynamoDB, Terraform, Node.js",
  "explanation": "The candidate has production experience with Node.js, but the duration in a backend-specific role appears to be around 1-2 years, below the 3-year threshold."
}

Run the screening flow on your own CVs

Create a free account, put a real job description in job.txt and a few anonymized resumes in the folder, then compare the shortlist with your recruiters’ own picks.

Scores, weights and mandatory requirements

The score is a weighted average you can recompute yourself: each criterion scores 1 when met, 0.67 when partly met, 0.33 for a weak hint and 0 when missing, multiplied by the criterion’s weight (3 essential, 2 important, 1 nice to have, 0 off) and divided by the sum of the weights. Criteria marked unknown are left out. Because the formula is fixed and the criteria are the same for everyone, scores from seperate calls for the same job can be compared.

A required criterion lowers the score but never removes anyone: each one clearly missing multiplies the score by 0.75 and is listed in required_missing. The program above flags those candidates instead of dropping them, so a recruiter confirms the reading before anyone is rejected. A required criterion marked unknown, listed in to_verify, is a question for the candidate, not a reason to reject.

Screening more than 10 applications

The Resume Scorer takes up to 100 resumes per call and answers right away up to 10 files and 50 resumes, in about a minute for 50. For a pool of 200 applications, the program parses each file, scores the stored resumes 50 at a time, sorts by score, then asks for a precise ranking of the top 10 side by side. Honestly, for many teams the score order is enough and the precise ranking is a nice extra: it adds a short reason comparing each finalist with the others, which helps when two profiles score close together.

If your product already has a search index, you can also pre-filter there (location, work authorization, availability) and only send the remaining applications to the Resume Scorer. Those filters are facts the candidate gave you, so they are easier to explain than a model’s judgement.

Keep a person in charge of the decision

Screening affects who gets a job interview, so build the review step before you build the automation. A few rules hold up well:

  • Show the evidence next to the number. A recruiter should see each criterion’s status and the sentence behind it, and be able to disagree.
  • Never auto-reject. Flag, sort and summarize; a person clicks the button that ends an application, and your product logs who did.
  • Review the criteria, not only the results. Most bad shortlists start with a requirement nobody needed, like a degree for a role that never used one.
  • Check the outcomes. Compare who gets advanced with who applied, by stage, and look into any gap you can’t explain.

In the EU, AI systems that filter applications or evaluate candidates are listed as high-risk under the AI Act, with obligations for providers and for the employers who deploy them. Our EU AI Act checklist for recruiting software goes through what that means for a screening feature. In the US, check the local rules that apply to automated employment decision tools where you hire, such as New York City’s bias audit requirement.

Production checklist

  • Call the APIs from a background job. The recruiter's screen reads stored results; it doesn't wait for a parse.
  • Keep the job_id and each application_id with your records. HireLayer stores the job, the resumes and their scores, so asking again for a pair already scored costs no credit.
  • Use your own application IDs as application_id, in the parse and in the score call, so every result maps back to a record.
  • Treat a 422 resume_unreadable or a 413 payload_too_large from the parser as a final outcome for that file (not a resume, unreadable, empty or too large) and route it to a person.
  • If HireLayer must not keep the files, the do_not_store_data option processes without storing anything. The ids then come back null, so send each resume as a file or as its parsed JSON, with a reference instead of an application_id.
  • Re-screen when the job changes. New criteria mean new scores; old ones should be marked out of date in your interface.

Finaly, measure before you roll out. Take a closed job with a known shortlist, run the program on its applications and compare the ouput with what your recruiters chose. Where they disagree, read the criterion explanations: they usually point to a requirement that needs rewording.

Frequently asked questions

What is AI resume screening?

Software that reads job applications and assesses them against the requirements of a role, usually by parsing the CV, comparing it with criteria taken from the job description and returning a score or an order. A recruiter then reviews the result and makes the decision.

Is AI resume screening better than keyword filtering?

It catches equivalent experience that a keyword filter misses, and it can say why a requirement is or isn’t met. It still needs a person to review the criteria and the shortlist, because it can misread a CV like any reader.

How many resumes can I screen in one API call?

The parser reads one file per call. The Resume Scorer scores up to 100 resumes for one job in a single call, and answers right away up to 10 files and 50 resumes; a larger call answers 202 with a results_url to read the scores from. Its precise ranking orders the 10 best side by side.

Can the screener reject candidates automatically?

The API returns statuses, scores and reasons; it never rejects anyone. We recommend flagging candidates who miss a mandatory requirement and letting a recruiter confirm, rather than rejecting them in code.

Which languages and file formats are supported?

The parser reads resumes in 70 languages and accepts PDF, Word, OpenDocument, PowerPoint, text, HTML, Markdown and image files, including scans. Job descriptions can be in any language.

Sources and further reading

  1. HireLayer API documentation: screening pipeline guide
  2. HireLayer API documentation: Resume Scorer
  3. HireLayer API documentation: Job Criteria Extractor
  4. EU AI Act, Annex III: high-risk AI systems
  5. NYC Department of Consumer and Worker Protection: Automated Employment Decision Tools

Louis Desclous

Updated on · Reading time: 10 minutes