---
title: "OpenAPI Reference"
description: "Generate and publish API reference docs from Farm.js API route metadata, with Scalar-style presentation."
canonical_url: "https://farmjs.dev/docs/0.1/openapi"
markdown_url: "https://farmjs.dev/docs/0.1/openapi.md"
last_updated: "2026-12-01"
x_farming_labs_generated_preamble: true
---

# OpenAPI Reference
URL: /docs/0.1/openapi
LLM index: /llms.txt
Description: Generate and publish API reference docs from Farm.js API route metadata, with Scalar-style presentation.

# OpenAPI Reference

Generate and publish API reference docs from Farm.js API route metadata, with Scalar-style presentation.

## Enable OpenAPI

**farm.config.ts**

```ts
export default defineConfig({
  openapi: {
    enabled: true,
    route: "/docs/reference",
    title: "Farm.js API",
    version: "1.0.0",
  },
});
```

## Reference route

The OpenAPI route can be included in generated route types so docs navigation and Link hrefs stay aware of the reference page.

Use an absolute pathname, such as `/docs/reference`. Farm.js rejects query strings, fragments,
backslashes, encoded separators, and dot segments such as `..` or `%2e%2e` that browsers
would reinterpret. Integration route paths and `workflows.route` use the same validation.

## What gets documented

Farm.js generates an OpenAPI 3.0.3 spec from the API routes it mounts under `/api`:
`src/app/api/**/route.ts` files, root `routes.ts` endpoints, programmatic API routes, and routes
that [plugins](/docs/0.1/plugins/create-plugin#typed-api-routes) register. Each operation carries the
route params, query schemas, body schemas, and response metadata its endpoint declares.
Programmatic routes outside `/api`, such as a sitemap, are not served beneath the API server and
are left out. The development server and `farm build` read the same route table, so
`/openapi.json` describes the same operations in both.

**src/app/api/users/route.ts**

```ts
import { createEndpoint } from "@farm.js/core/api";
import { z } from "zod";

export const GET = createEndpoint(
  {
    method: "GET",
    query: z.object({
      limit: z.coerce.number().int().positive().default(20),
    }),
  },
  async ({ query }) => {
    return Response.json({
      users: await listUsers(query.limit),
    });
  },
);
```

The route appears in the generated reference with a typed `limit` query parameter.

Dynamic API segments use OpenAPI path parameters. Optional catch-all routes such as
`/api/files/[[...slug]]` produce both `/files` and `/files/{slug}` operations because OpenAPI path
parameters themselves must always be required. Required catch-all routes produce only the
parameterized operation.

A body declared with `multipart()` is documented as `multipart/form-data`, and its file fields
(`z.file()`, `z.instanceof(File)`, or `z.instanceof(Blob)`) as `format: binary` parts. Each operation
has a unique `operationId` (`get_users_id`). When two routes would share one, as `/api/a_b` and
`/api/a/b` do, the later operation gets a numbered suffix (`get_a_b_2`).

`QUERY` routes include their request-body schema too. Farm.js currently emits OpenAPI 3.0.3, whose
Path Item Object does not have a native `query` field. To keep the document valid, Farm.js places each
`QUERY` Operation Object under the registered `x-oai-additionalOperations.QUERY` extension. This
maps directly to the native `query` field available in OpenAPI 3.2 without mislabeling the route as
`GET` or `POST`.

## Hide a route

Every mounted route is documented unless it opts out. Leave internal routes, such as an admin
login or a telemetry collector, out of the document with `hidden`:

**src/app/api/admin/session/route.ts**

```ts
export const openapi = { hidden: true };

export async function POST(request: Request) {
  return signIn(request);
}
```

A route file's `openapi` export applies to every method that file exports, including plain
`export function GET` handlers. Type it with `RouteOpenAPIConfig` from `@farm.js/core/api` if
you want the editor to check it. Farm.js rejects any other option in this export, so a misspelled
`{ hide: true }` fails discovery instead of publishing the route.

A typed endpoint can hide one method instead:

```ts
export const DELETE = createEndpoint({ method: "DELETE", openapi: { hidden: true } }, async () => ({
  deleted: true,
}));
```

Endpoint metadata wins over the file export. Plugin routes take the same `openapi` option in
their route definition. Hiding a route only removes it from the document: the route is still
served, so protect it with middleware or authentication.

## Describe routes Farm.js does not mount

Some routes are served outside Farm.js's route table, for example the docs engine's `/api/docs`.
Describe them with `openapi.paths`, written as OpenAPI 3.0 Path Item Objects:

```ts
export default defineConfig({
  openapi: {
    enabled: true,
    paths: {
      "/docs": {
        get: {
          summary: "Search the documentation",
          parameters: [{ name: "query", in: "query", schema: { type: "string" } }],
          responses: { 200: { description: "Matching sections" } },
        },
      },
    },
  },
});
```

Keys are relative to the API server, like the generated paths, so `/docs` is `/api/docs` on the
default `/api` server. Farm.js adds these entries as written. An operation that Farm.js already
generates from a mounted route is an error rather than a silent override; hide the route first
if you want to describe it by hand.

## Add metadata

```ts
export default defineConfig({
  openapi: {
    enabled: true,
    route: "/docs/reference",
    title: "Acme API",
    description: "Public and internal API routes for Acme.",
    version: "1.0.0",
    servers: [
      {
        url: "https://api.acme.com",
        description: "Production",
      },
    ],
    contact: {
      name: "API Support",
      email: "support@acme.com",
    },
  },
});
```

## Serve the reference

The configured route serves a Scalar-powered reference page with the generated spec embedded in the page. The route can be visited during development and included in production docs.

Farm.js pins the Scalar browser assets to the reviewed version shipped with the framework and verifies CDN responses with subresource integrity. Scalar upgrades therefore arrive with Farm.js releases instead of floating independently in production.

## Choose the API server URL

Set `openapi.servers` when the document must advertise an explicit public server. Otherwise Farm.js
uses an absolute `api.baseURL` when configured. During development, a root-relative API base is
joined to the current request origin (or `http://localhost:3000` when generating without a
request). Production documents keep a root-relative API base relative, so deployed clients and the
interactive reference stay on the deployment's current origin instead of pointing at localhost.

The precedence is `openapi.servers`, an absolute Farm.js `api.baseURL`, the current development
request origin plus Farm.js's API path, then the mode-specific default.

## Describe authentication

OpenAPI operations are public by default because Farm.js cannot infer authorization from arbitrary
middleware. Set a document-wide default with `openapi.security`, then override individual typed
endpoints when public and protected routes share one document:

```ts
export default defineConfig({
  openapi: { enabled: true, security: "cookie" },
});

export const GET = createEndpoint({ method: "GET", openapi: { security: "public" } }, async () => ({
  status: "ok",
}));

export const POST = createEndpoint(
  { method: "POST", openapi: { security: "bearer" } },
  async () => ({ created: true }),
);
```

Supported modes are `public`, `bearer`, `cookie`, and `either`. This metadata documents the
contract; authentication middleware must still enforce it at runtime.

## Describe responses

Farm.js does not guess status codes or body formats from arbitrary handler code. Add response metadata
to a typed endpoint when clients need an exact contract:

```ts
export const GET = createEndpoint(
  {
    method: "GET",
    openapi: {
      responses: {
        200: {
          body: "json",
          description: "Current account",
          schema: {
            type: "object",
            properties: { id: { type: "string" } },
            required: ["id"],
          },
        },
        404: { body: "empty", description: "Account not found" },
      },
    },
  },
  async () => Response.json(await getAccount()),
);
```

Use `body: "empty"` for responses without content, `body: "stream"` with an explicit
`contentType` for streams, and `body: "binary"` for files. JSON and binary responses default to
`application/json` and `application/octet-stream`. When response metadata is absent, Farm.js emits an
unspecified default response instead of claiming an unknown status code or JSON schema.

**Terminal**

```bash
farm generate
farm build
```

`farm dev` and `farm generate` keep route types aware of the reference URL. `farm build` includes the reference route in the app output when OpenAPI is enabled.

## Production notes

- Enable OpenAPI for APIs you want to document publicly or internally.
- Hide private admin and machine-to-machine routes with `openapi: { hidden: true }` unless the
  document is for internal readers only.
- Use Zod schemas on API routes for better generated parameter and body details.
- Farm.js recognizes Zod schemas structurally, including Zod 3/4 schemas loaded from another package
  copy. Standard Schema validators without portable schema metadata remain valid at runtime, but
  the generated document uses an explicit metadata-unavailable fallback instead of inventing a
  shape.
- Query parameters and request bodies are documented by what the client sends. A field that uses
  `.transform()`, `.pipe()`, or `z.preprocess()` keeps its input schema's type, `enum`,
  constraints, and optionality, so `z.enum(["open", "done"]).transform(...)` still lists its
  allowed values.
- Pair OpenAPI with typed callers so server/client code and published docs describe the same route surface.

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
Docs-scoped sitemap: [/docs/sitemap.md](/docs/sitemap.md).
Well-known sitemap: [/.well-known/sitemap.md](/.well-known/sitemap.md).
