GitHub 0
Skip to content

API routes

respond answers one route in the form the request picked, from one value or function per form, with your status and headers.

respond(request, renders, init?) answers one route. Each key of renders is a form the route offers, and the first key is the default.

import { H3, defineHandler } from "h3";
import { whoasks } from "whoasks";
import { middleware } from "whoasks/h3";

interface Result {
  ok: boolean;
  url: string;
  errors: { code: string; message: string; fix: string }[];
}

// Stands for your own check.
async function validate(url: string | null): Promise<Result> {
  const errors = [{ code: "E1", message: "Missing title", fix: "Add a <title>" }];
  return { ok: false, url: url ?? "", errors };
}

const agentText = (r: Result): string =>
  [
    `${r.ok ? "ok" : "failed"} validate ${r.errors.length} errors, ${r.url}`,
    ...r.errors.map((e) => `error ${e.code} ${e.message}. fix: ${e.fix}`),
  ].join("\n");

const site = whoasks();

export const app: H3 = new H3().use(middleware(site));

app.get(
  "/api/validate",
  defineHandler(async (event) => {
    const result = await validate(event.url.searchParams.get("url"));
    return site.respond(event.req, {
      json: result,
      markdown: () => agentText(result),
    });
  }),
);
app.ts

Each client gets the form its request picked:

ClientContent-Type
curl, Codexapplication/json
Claude Code, Cursortext/markdown; charset=utf-8
Accept: text/plaintext/plain; charset=utf-8, the same text

For ?url=https://a.dev, an agent gets this text:

failed validate 1 errors, https://a.dev
error E1 Missing title. fix: Add a <title>
text

respond works without h3 too. It takes a Web Request and returns a Response.

The keys are form names: html, markdown, json, and the names your layers add.

Key order is the order of the offers. { json, markdown } answers Accept: */* with JSON, and { markdown, json } answers it with Markdown.

A key that names no form throws whoasks: no form named "yaml".

ValueWhat is sent
A stringThe string as the body
A ResponseThat response, with its own status and headers, plus Vary
Anything elseJSON.stringify of it
A functionIts return value, by the rows above. It runs only when its form is picked

A function may be async. Put expensive work in a function, so a request that picks JSON does not build the Markdown.

For a string or a JSON value, Content-Type is the picked type. A text/* type gets ; charset=utf-8, and application/json does not.

A Response keeps its own Content-Type. whoasks does not change it.

return site.respond(
  request,
  { json: problem, markdown: () => `failed validate. ${problem.title}` },
  { status: 422, headers: { "cache-control": "no-store" } },
);
ts

init is a ResponseInit. Its status and headers apply to the answer in whichever form is picked.

init does not apply to a value that is a Response. Every answer carries Vary: Accept.

return site.respond(request, {
  html: () => `<main><h1>${guide.title}</h1><p>${guide.body}</p></main>`,
  json: guide,
});
ts

With an html key and no markdown key, respond also offers markdown, last, and makes it from the HTML with the converter. The derived Markdown keeps the status from init.

With no converter (whoasks/core, or convert: false), nothing is derived, and Accept: text/markdown gets the HTML.

Add a markdown key to write the Markdown yourself. It then wins over conversion.

const site = whoasks({ strict: true });
ts

By default, a request that allows nothing offered gets the first key. Accept: image/png on the route above gets JSON.

With strict: true, respond answers 406. The body is text/plain and lists the offered media types, one per line:

application/json
text/markdown
text/x-markdown
text/plain
text

No function in renders runs for a 406.

strict applies to respond only. handle never refuses, so pages, images, and other routes behind it are unaffected.

A twin or ?format= does not bypass this. /api/validate.md with Accept: text/html allows nothing offered, so a strict site answers it 406.

Behind handle (or the h3 middleware), /api/validate.md and /api/validate?format=md reach the route as /api/validate, and the route answers with its own Markdown.

A route that offers both html and markdown keeps its own Markdown on the twin. handle does not convert the HTML instead.

?format=json works on a route that offers json: respond reads it from the URL.

A plain JSON route that does not call respond is untouched by handle, and gets no Vary.

A route can offer a form of your own, such as YAML or application/problem+json. See Add a form.