Skip to content

M5-S3 — Ship a headless client: the careers site

Section titled “M5-S3 — Ship a headless client: the careers site”
ModuleM5 — The API and an external client
After this session you canArchitect, build and secure a client that uses the platform as its back end, and ship it from test to production unchanged.
TimeFacilitated: 56 min · On your own: 56 min
Before you startM5-S2: BASE, TOKEN, FEED from M5-S1; Hala Mansour’s session in .tokens.json. The application-check validator from M4-S2 attached.
Go deeperThe backend cluster · Writing data · Errors and retries

◆ Orientation (1 min) — From calls to a client

Section titled “◆ Orientation (1 min) — From calls to a client”

You have proved single calls. The agency’s careers site needs a program that does them all day, under load, against two environments, and fails well. In this session you write the part of it that every such program needs and that the agency will copy: one transport seam, a read path, a write path with a CV, and the configuration that lets the same code run against test and production. Then you hand it over with a contract.

▤ Concept (6 min) — The shape of a good headless client

Section titled “▤ Concept (6 min) — The shape of a good headless client”

One seam for everything that crosses the wire

Section titled “One seam for everything that crosses the wire”
flowchart TB
  APP["Careers site code:<br/>list jobs, submit an application"] --> SEAM
  subgraph SEAM["The transport seam (one function)"]
    C["Base URL and credential<br/>from configuration"] --> U["Unwrap by shape"] --> E["Errors become objects:<br/>status, code, traceId, details"] --> R["Retry policy<br/>by status and method"]
  end
  SEAM --> GW["Tenant host /api"]

What to notice: everything that knows about HTTP lives in one place; the code above it handles jobs and applications, never status codes or envelopes.

Read through a view built for the client, never the plain entity list (M5-S1). Send a limit on every list, page with skip, and order on a stable key with the id last. Ask for only the fields you need; a projected single read is lighter. A view can publish its own OpenAPI document: turn on Swagger document in the view’s display options, and GET /api/v1/views/{viewId}/openapi.json describes exactly the five operations of that view, with the record’s value schema following the view’s fields. It is a narrower, steadier contract to generate types from than the whole platform’s. The document itself is not wrapped; the operations it describes are.

A record’s file field holds a file descriptor, not bytes. Upload first, then write:

  1. POST /api/storage/v2/files?temp=true with the file in the multipart field file. The answer’s result is an array of descriptors (id, name, mimeType, size).
  2. Create the record with the descriptor as the field’s value, within the day. Saving promotes the temporary file to permanent; an expired temporary file fails the save with FILE_EXPIRED.

Refusals tell you what to do:

RefusalMeaningThe client’s answer
400 ALL_ENTRY_VALIDATION_ERROR or ENTRY_VALIDATION_ERRORFields failed the entity’s rules; result.details names themShow the person which fields; never retry unchanged
A validator’s refusalYour own Function said no (M4-S2)Show its message
400 UNIQUE_VALUEA unique field already has this valueTreat as real data, not a glitch
409 UPDATE_CONFLICTSomeone changed the record since you read it (you sent its updateIdentifier)Re-read, re-apply, then save
403The credential’s user lacks accessStop; ask for access

Anonymous visitors writing through a public form may be asked to prove they are human (a puzzle the browser solves); a server-side client with its own credential is never asked.

StatusRetry?
400, 403, 404, 422Never unchanged
401Refresh the credential once and retry once (OAuth); an API token cannot be refreshed, so stop
409Re-read first; never on a timer
429, 502, 503, 504Yes, with backoff; a Retry-After header is the minimum wait
500 with a catalogued codeNo: it is a fixed answer; report it with its traceId

Back off with full jitter: wait a random time between 0 and min(60 s, 1 s × 2^attempt), at most five attempts. A failure before the request was sent is always safe to retry; a timeout after sending is not, because the write may have happened: reconcile first, for example by looking for the record before creating it again. Send your own X-Correlation-Id per operation; the platform echoes it and uses it as the traceId, so your logs and theirs share one key.

Between test and production exactly two things change: the base URL (the host is the tenant) and the credential (one application user per environment). Both are injected at deploy time; one build artifact is promoted unchanged, and no credential is ever baked into it or committed. Check the host before any write: a job pointed at the wrong host writes to the wrong tenant.

The gateway removes or overwrites identity headers a client sends (x-user-id, x-space-id, x-view-id and the platform’s internal key), so a client can neither choose who it is nor which tenant it reaches. It acts through views and its own credential, nothing else.

Goal. A client that lists open jobs page by page, submits an application with a CV, reports a validator’s refusal with its trace id, and reads its configuration from the environment only.

Before you start. Your terminal in a new folder, careers-client.

The intake door

  1. Open Job Application › Views › New View Careers intake: Source view Entries, Fields: the Candidate information block’s fields. Turn on Creating new entries with an After Save. No list, edit or archive. Under the display options, turn on Swagger document.
  2. Access Permission Authenticated, Select Users Careers Site. Save, Publish, and note its id as INTAKE.

Learn the value shapes

  1. Fetch the intake’s contract with the careers token and look at the value schema: curl -s "$BASE/api/v1/views/$INTAKE/openapi.json" -H "x-app-token: $TOKEN" | jq '.paths | keys'.

  2. Read one real application as Hala Mansour, through the starter’s HR view (note its id as HRVIEW), and keep the shapes of the reference and phone fields:

    Terminal window
    curl -s -G "$BASE/api/v1/v/$HRVIEW/v3/entities/job_application/entries" \
    -H "Authorization: Bearer $(jq -r .access_token .tokens.json)" \
    --data-urlencode 'filterCriteria={"limit":1}' \
    | jq '.entries[0].value | {phone_number, nationality, key_skills}' > sample-application.json

    (If it answers 401, run your refresh.mjs from M5-S2 first.)

The client

  1. Create careers-client.mjs:

    import fs from 'node:fs';
    import crypto from 'node:crypto';
    const { CAREERS_BASE: BASE, CAREERS_TOKEN: TOKEN,
    CAREERS_FEED_VIEW: FEED, CAREERS_INTAKE_VIEW: INTAKE } = process.env;
    if (!BASE || !TOKEN || !FEED || !INTAKE) throw new Error('missing configuration');
    const RETRYABLE = new Set([429, 502, 503, 504]);
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    const backoff = (attempt) => Math.random() * Math.min(60_000, 1000 * 2 ** attempt);
    export class ApiError extends Error {
    constructor(status, body) {
    super(`${status} ${body?.error?.code ?? 'UNKNOWN'}`);
    this.status = status;
    this.code = body?.error?.code;
    this.traceId = body?.error?.traceId;
    this.details = body?.result?.details; // read defensively
    }
    }
    // The one transport seam.
    async function call(method, path, { query = {}, json, form } = {}) {
    const url = new URL(BASE + path);
    for (const [k, v] of Object.entries(query)) {
    url.searchParams.set(k, typeof v === 'string' ? v : JSON.stringify(v));
    }
    const correlation = crypto.randomUUID();
    for (let attempt = 0; ; attempt++) {
    let res;
    try {
    res = await fetch(url, {
    method,
    headers: {
    'x-app-token': TOKEN,
    'x-correlation-id': correlation,
    ...(json ? { 'content-type': 'application/json' } : {}),
    },
    body: json ? JSON.stringify(json) : form,
    });
    } catch (networkError) {
    // We cannot tell whether a write arrived: retry reads only.
    if (method !== 'GET' || attempt >= 4) throw networkError;
    await sleep(backoff(attempt));
    continue;
    }
    const text = await res.text();
    const body = text ? JSON.parse(text) : null;
    if (res.ok) {
    return body && typeof body === 'object' && body.success === true ? body.result : body;
    }
    if (RETRYABLE.has(res.status) && attempt < 4) {
    const floor = Number(res.headers.get('retry-after') ?? 0) * 1000;
    await sleep(Math.max(floor, backoff(attempt)));
    continue;
    }
    throw new ApiError(res.status, body);
    }
    }
    export async function listOpenJobs(pageSize = 50) {
    const jobs = [];
    for (let skip = 0; ; skip += pageSize) {
    const page = await call('GET', `/api/v1/v/${FEED}/v3/entities/jobs/entries`, {
    query: { filterCriteria: { limit: pageSize, skip, order: ['value.registration_deadline ASC', 'id ASC'] } },
    });
    jobs.push(...page.entries);
    if (page.entries.length < pageSize) return jobs;
    }
    }
    export async function uploadTemp(filePath, mimeType) {
    const form = new FormData();
    form.append('file', new Blob([fs.readFileSync(filePath)], { type: mimeType }), filePath.split('/').pop());
    const [descriptor] = await call('POST', '/api/storage/v2/files', { query: { temp: 'true' }, form });
    return descriptor;
    }
    export function submitApplication(value) {
    return call('POST', `/api/v1/v/${INTAKE}/v1/entities/job_application/entries`, { json: { value } });
    }
  2. Create a small test CV: printf '%%PDF-1.4\n%%EOF\n' > cv-tariq.pdf.

  3. Create try-careers.mjs:

    import fs from 'node:fs';
    import { listOpenJobs, uploadTemp, submitApplication, ApiError } from './careers-client.mjs';
    const jobs = await listOpenJobs(1); // page size 1 to prove the paging loop
    console.log('open jobs:', jobs.map((j) => j.value.job_title.en));
    const job = jobs.find((j) => j.value.job_title.en === 'Senior Software Engineer');
    const sample = JSON.parse(fs.readFileSync('sample-application.json', 'utf8'));
    const cv = await uploadTemp('./cv-tariq.pdf', 'application/pdf');
    const value = {
    full_name: { en: 'Tariq Mansour', ar: 'طارق منصور' },
    email: 'tariq.mansour@example.org',
    phone_number: sample.phone_number,
    nationality: sample.nationality,
    key_skills: sample.key_skills,
    vacancy: { dataEntity: job.dataEntity, dataEntry: job.id },
    cv,
    available_from: '2027-01-10',
    expected_salary: '15000',
    };
    for (const attempt of [value, { ...value, email: 'tariq.late@example.org', available_from: '2020-01-01' }]) {
    try {
    const created = await submitApplication(attempt);
    console.log('created application', created.id);
    } catch (e) {
    if (!(e instanceof ApiError)) throw e;
    console.log('refused:', e.status, e.code, '| trace', e.traceId, '|', JSON.stringify(e.details ?? null));
    }
    }
  4. Set the configuration and run it:

    Terminal window
    export CAREERS_BASE="$BASE" CAREERS_TOKEN="$TOKEN" CAREERS_FEED_VIEW="$FEED" CAREERS_INTAKE_VIEW="$INTAKE"
    node try-careers.mjs

    It prints both open jobs, created application with an id, then refused with the validator’s refusal and a trace id. The refusal is a 400 with the code ALL_ENTRY_VALIDATION_ERROR; its details name the validator and its reason.

  5. As Hala Mansour, open the Inbox: Tariq Mansour’s application is waiting at Request processing, with his CV attached.

  6. Unset CAREERS_TOKEN and run again: the client refuses to start with missing configuration, before any call.

Check.

  • The client lists both open jobs through Careers feed with a page size of 1.
  • Tariq Mansour’s application was created with his CV and is in HR’s Inbox.
  • The second submission was refused by your validator, printed with its code and trace id.
  • No host, token or view id appears in the code; all four come from the environment.
  • Nothing in the client sets an identity or tenant header.

Pass condition. One program, configured only by environment variables, reads open jobs, creates an application with a CV through the intake view, and reports a refusal with its trace id.

If something goes wrong

What you seeWhat to do
403 on the createCareers intake is not published for Careers Site, or Creating new entries is off.
ALL_ENTRY_VALIDATION_ERROR naming fieldsRead details: a required field is missing or has the wrong shape. Compare it with sample-application.json and the view’s OpenAPI document.
FILE_EXPIREDThe temporary upload is more than a day old or the id is wrong: upload again.
The upload is refused as an invalid fileThe file content does not match its type: create the PDF again with step 6.
Both submissions were createdThe validator is not attached before a new record is saved (M4-S2).
401 in step 4Hala’s access token expired: run refresh.mjs.
Model answer

The client’s architecture is what you hand to the agency: one call function owns the credential, the correlation id, unwrap by shape, the error object and the retry policy; it retries reads on network failures and only 429 and 5xx gateway statuses with full-jitter backoff and Retry-After as a floor, and never retries a write blindly. The read path pages through the view on a stable order. The write path uploads the CV as a temporary file and creates the application with its descriptor, so the save makes the file permanent. The validator’s refusal arrives as a typed error with the field details and the trace id, which the site turns into a message for the candidate. Promotion changes four environment variables and nothing else.

◇ Worked scenario (2 min) — Going live

Section titled “◇ Worked scenario (2 min) — Going live”

The agency is ready for production. Decide each step before reading on.

1. The credential. Decision: a new application user Careers Site in production with its own token, the base system level, and access to production’s Careers feed and Careers intake only. The test token is never copied across.

2. The views. Their ids differ per environment, because the views are created by the package in M8. Decision: the view ids are configuration too, next to the base URL and the token.

3. The artifact. Decision: the same build that passed in test, promoted unchanged; a deployment-time check that CAREERS_BASE is the production host before the first write.

4. The day it fails. A Monday-morning spike returns 429 with Retry-After: 2. Decision: the seam already waits at least two seconds with jitter, so ten servers do not retry together. The agency’s monitoring alerts on repeated 5xx with catalogued codes, which are reported, not retried.

The contract you hand over is short: two views, one credential per environment, the four variables, the retry table, and “branch on error.code, quote traceId”.

✓ Practice (6 min) — Check your client

Section titled “✓ Practice (6 min) — Check your client”
PracticeChoose one answer.

A client’s create call times out after sending. What should it do before trying again?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the request was sent, so the record may already exist. See the retry policy.

  2. Explanation for B

    ✓ Correct

    Correct: a timeout after sending is not safe to retry blindly; reconcile first. See the retry policy.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a timeout carries no Retry-After, and the danger is a duplicate, not load. See the retry policy.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A client attaches a file by putting the file’s bytes, base64-encoded, in the record’s file field. The save is refused. What is the right flow?

  1. Explanation for A

    ✗ Incorrect

    Not this one: entries take values, and a file field’s value is a descriptor. See the write path.

  2. Explanation for B

    ✓ Correct

    Correct: upload first (temporary), then save the record with the descriptor, which makes the file permanent. See the write path.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the size is not the problem; a file field never holds bytes. See the write path.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose every answer that applies.

Which of these should change when the careers client is promoted from test to production? Choose all that apply.

  1. Explanation for A

    ✓ Correct

    Correct: the host selects the tenant, so production has its own. See environments and the security boundary.

  2. Explanation for B

    ✓ Correct

    Correct: each environment has its own application user and token. See environments and the security boundary.

  3. Explanation for C

    ✗ Incorrect

    Not this one: one artifact is promoted unchanged; a code change per environment means something leaked into it. See environments and the security boundary.

  4. Explanation for D

    ✓ Correct

    Correct: the views are recreated in production, so their ids differ and belong in configuration. See the worked scenario.

Check your answer

The correct answers are A, B and D. Open the explanation under each option to see why.

PracticeChoose one answer.

A developer proposes sending x-user-id with each call so that applications appear as created by the candidate’s HR contact. What happens?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the gateway overwrites identity headers from the validated credential. See environments and the security boundary.

  2. Explanation for B

    ✓ Correct

    Correct: a client cannot choose who it is; identity comes only from its credential. See environments and the security boundary.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the header is silently cleared and set again, not refused. See environments and the security boundary.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

Where should a careers client get the field types of the records it creates through Careers intake?

  1. Explanation for A

    ✓ Correct

    Correct: it describes exactly that view’s operations and its value schema, a narrow and steady contract. See the read path.

  2. Explanation for B

    ✗ Incorrect

    Not this one: it is much wider than the client needs and changes with every area. See the read path.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the portal is a different client with different views; its traffic is no contract. See the read path.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

You built and secured a client around one seam, wrote records with files from outside, turned every refusal into an action, and know exactly what changes between environments. After Module 5 you can integrate over the HTTP API with the right credential, and architect, build, secure and ship an external client against it.

Next. Module 6 reverses the direction: the suite tells other systems what happened, and a screen stays live without asking.