M5-S3 — Ship a headless client: the careers site
Section titled “M5-S3 — Ship a headless client: the careers site”| Module | M5 — The API and an external client |
| After this session you can | Architect, build and secure a client that uses the platform as its back end, and ship it from test to production unchanged. |
| Time | Facilitated: 56 min · On your own: 56 min |
| Before you start | M5-S2: BASE, TOKEN, FEED from M5-S1; Hala Mansour’s session in .tokens.json. The application-check validator from M4-S2 attached. |
| Go deeper | The 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.
The read path
Section titled “The read path”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.
The write path
Section titled “The write path”A record’s file field holds a file descriptor, not bytes. Upload first, then write:
POST /api/storage/v2/files?temp=truewith the file in the multipart fieldfile. The answer’sresultis an array of descriptors (id,name,mimeType,size).- 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:
| Refusal | Meaning | The client’s answer |
|---|---|---|
400 ALL_ENTRY_VALIDATION_ERROR or ENTRY_VALIDATION_ERROR | Fields failed the entity’s rules; result.details names them | Show the person which fields; never retry unchanged |
| A validator’s refusal | Your own Function said no (M4-S2) | Show its message |
400 UNIQUE_VALUE | A unique field already has this value | Treat as real data, not a glitch |
409 UPDATE_CONFLICT | Someone changed the record since you read it (you sent its updateIdentifier) | Re-read, re-apply, then save |
403 | The credential’s user lacks access | Stop; 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.
The retry policy
Section titled “The retry policy”| Status | Retry? |
|---|---|
400, 403, 404, 422 | Never unchanged |
401 | Refresh the credential once and retry once (OAuth); an API token cannot be refreshed, so stop |
409 | Re-read first; never on a timer |
429, 502, 503, 504 | Yes, with backoff; a Retry-After header is the minimum wait |
500 with a catalogued code | No: 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.
Environments and the security boundary
Section titled “Environments and the security boundary”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.
⛏ Lab (40 min) — The careers client
Section titled “⛏ Lab (40 min) — The careers client”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
- 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.
- Access Permission Authenticated, Select Users Careers Site. Save, Publish,
and note its id as
INTAKE.
Learn the value shapes
-
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'. -
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 yourrefresh.mjsfrom M5-S2 first.)
The client
-
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 } });} -
Create a small test CV:
printf '%%PDF-1.4\n%%EOF\n' > cv-tariq.pdf. -
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 loopconsole.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));}} -
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.mjsIt 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. -
As Hala Mansour, open the Inbox: Tariq Mansour’s application is waiting at Request processing, with his CV attached.
-
Unset
CAREERS_TOKENand run again: the client refuses to start with missing configuration, before any call.
Check.
- The client lists both open jobs through
Careers feedwith 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 see | What to do |
|---|---|
403 on the create | Careers intake is not published for Careers Site, or Creating new entries is off. |
ALL_ENTRY_VALIDATION_ERROR naming fields | Read details: a required field is missing or has the wrong shape. Compare it with sample-application.json and the view’s OpenAPI document. |
FILE_EXPIRED | The temporary upload is more than a day old or the id is wrong: upload again. |
| The upload is refused as an invalid file | The file content does not match its type: create the PDF again with step 6. |
| Both submissions were created | The validator is not attached before a new record is saved (M4-S2). |
401 in step 4 | Hala’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”A client’s create call times out after sending. What should it do before trying again?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Which of these should change when the careers client is promoted from test to production? Choose all that apply.
Check your answer
The correct answers are A, B and D. Open the explanation under each option to see why.
A developer proposes sending x-user-id with each call so that applications appear as created by
the candidate’s HR contact. What happens?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Where should a careers client get the field types of the records it creates through Careers intake?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
↺ Recap (1 min) — After Module 5
Section titled “↺ Recap (1 min) — After Module 5”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.