Skip to Content
hono-bento

Consuming schemas

Build a typed client in another app that validates requests and parses responses with the API's own schemas.

The schemas package is the API's contract. Any app in the monorepo can import it: a web app, a CLI, a worker, an SDK. If you validate requests and parse responses with it, a contract change becomes a type error in every app, not a surprise in production.

A typed client

This is a trimmed version of the client in the example's apps/cli:

apps/cli/src/client.ts
import { type Todo, type TodoCreate, todoCreateSchema, todoSchema } from '@todos/schemas/todos';
import type { ZodType } from 'zod';

export class ApiError extends Error {
  constructor(
    readonly status: number,
    readonly type: string,
    message: string
  ) {
    super(message);
  }
}

export function createClient({ baseUrl, apiKey }: { baseUrl: string; apiKey: string }) {
  async function call<T>(method: string, path: string, schema: ZodType<T>, body?: unknown): Promise<T> {
    const response = await fetch(new URL(path, baseUrl), {
      method,
      headers: { 'x-api-key': apiKey, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    const json: unknown = await response.json();
    if (!response.ok) {
      const { error } = json as { error?: { type?: string; message?: string } };
      throw new ApiError(response.status, error?.type ?? 'unknown', error?.message ?? response.statusText);
    }
    return schema.parse(json);
  }

  return {
    todos: {
      // Validate the input before sending, with the schema the API validates with.
      create: async (input: TodoCreate): Promise<Todo> =>
        call('POST', '/v1/todos', todoSchema, todoCreateSchema.parse(input)),
      retrieve: async (id: string): Promise<Todo> => call('GET', `/v1/todos/${encodeURIComponent(id)}`, todoSchema),
    },
  };
}

A typed Hono client

When the calling app is TypeScript and lives beside the API, Hono's own client, hc from hono/client, can call the API with no client code at all. mountSpecs returns the app typed with every route: its path, method, path params, query, body, and one response per documented status, typed from the same schemas. Export that type from the API:

apps/api/src/app.ts
export function createApp({ db }: CreateAppOptions) {
  const app = mountSpecs(new Hono(), specs, { strategies, authorizer, deps: () => ({ db }) });
  // ...
  return app;
}

export type AppType = ReturnType<typeof createApp>;

and import it, as a type only, in the app that calls the API:

import { hc } from 'hono/client';

import type { AppType } from '../../api/src/app';

const client = hc<AppType>('https://api.example.com', { headers: { 'x-api-key': apiKey } });

const res = await client.v1.todos[':id'].$patch({ param: { id }, json: { done: true } });
if (res.status === 200) {
  const todo = await res.json(); // { object: 'todo'; id: string; title: string; done: boolean; ... }
}

The types follow the contracts:

  • Bodies and queries are what the route's validation schemas accept: a missing field or a wrong enum value is a type error. A form-data route takes form instead of json.
  • Responses are typed per status, as each schema's input once serialized to JSON: a Date arrives as a string. Check res.status to narrow to one. A response whose content isn't JSON (text/csv) has an untyped body.
  • Errors the framework sends itself (401, 403, 400 validation errors) aren't in the types unless the route documents them in responses.

This needs each spec declared as defineSpec({ ... }), without a type argument, so it can record its routes' types. A spec declared as defineSpec<Identity>({ ... }) still works, but adds nothing to the client.

hc checks types only. Nothing validates what the server sends, so for an app deployed separately from the API, such as a CLI, parse responses with the schemas, as above. The example's todos tests call the API through hc<AppType>.

Errors

Every hono-bento error response has the same shape (see Errors):

{ "error": { "type": "not_found", "message": "No todo found with id 'todo_x'." }, "status": 404 }

so one ApiError class covers every endpoint.

Should clients parse responses?

Parsing every response costs a little CPU, and it catches a server that has drifted from the contract. For a first-party app built from the same commit as the API, you can use the inferred types alone (type Todo) and skip .parse(). For anything deployed separately, like a CLI on a user's machine, parse.

On this page