Skip to content
✨ Publier v1 is live — a polished docs platform built for the open web.
On this page

OpenAPI

Generate OpenAPI 3.x MDX pages and use the partial AsyncAPI content-source and rendering APIs.

@publier/openapi generates MDX pages from OpenAPI specs and provides API rendering components. AsyncAPI support is a separate, partial content-source and component API, described below.

An API reference is one kind of generated reference. A CLI reference is generated the same way, from a usage spec, with integrations.cli. An SDK reference is generated from the library’s own documentation tool, with integrations.sdk.

Install

Terminal window
pnpm add @publier/openapi

integrations.openapi needs @publier/openapi installed in the site.

Quickstart

    1. Place your spec in the project, for example specs/api.openapi.yaml:

      specs/api.openapi.yaml
      openapi: "3.1.0"
      info:
      title: My API
      version: "1.0.0"
      tags:
      - name: Users
      - name: Orders
      paths:
      /users:
      get:
      operationId: listUsers
      summary: List users
      tags: [Users]
      responses:
      "200":
      description: A list of users
    2. Declare it in publier.config.yaml:

      publier.config.yaml
      integrations:
      openapi:
      - spec: ./specs/api.openapi.yaml
      path: /docs/api

      spec is a project-relative path or an https:// URL. path is the route the generated pages live under: it must sit below /docs and defaults to /docs/api. A bare string, openapi: ./specs/api.openapi.yaml, means path: /docs/api. List several entries for several specs; each needs its own path, and two entries cannot share a path or nest one inside the other.

    3. Run publier dev or publier build. Publier validates each spec and writes one page per operation to src/content/docs/<path>/<tag>/<operation>.mdx, so the example above gives /docs/api/users/list-users. The operation slug is the operationId in kebab-case. When the operationId contains dots, as in specs generated from protobuf (acme.authz.v1.FactService.WriteFacts), only the last segment is used (write-facts). If two operations in one tag would end up with the same slug, each takes one more segment from the end (fact-service-get, v1-fact-service-get, and so on) until they differ. The pages render with interactive components for parameters, request bodies, responses and code samples. Every description in the spec is rendered as CommonMark (paragraphs, inline code, lists, links); raw HTML in it shows as text, and a link to anything but http:, https:, mailto:, an #anchor or a relative path keeps only its text. An operation’s title, its sidebar label and page heading, is its summary when that is one line of at most 80 characters. Specs generated from protobuf often put a whole paragraph of the method’s comment in summary; the title is then the words of the operationId’s last segment (Finalize import for acme.ImportService.FinalizeImport), or METHOD path when there is no operationId, and the summary text leads the page instead. The first paragraph of the description (after any such summary), as plain text, is the page’s lead, meta description and search summary, so write it to stand on its own. The lead is set in large type, so keep it to a sentence or two and put the detail in the paragraphs after it. The page body continues with the rest of the description, below the request line, so the lead is not said twice.

The default docs sidebar lists each tag as a group, labelled with the tag’s name and in the order of the spec’s top-level tags list. You do not need docs.sidebar.meta entries for them.

Versions and products

A generated page is an ordinary docs page at its path, so its product, version, version status (frozen or archived banner, canonical link to the current version, search partition) come from your navigation by path prefix, as for a hand-written page there. To document two versions of an API, give each its own spec and path under that version:

publier.config.yaml
integrations:
openapi:
- { spec: ./specs/v2.openapi.yaml, path: /docs/compute/v2/api }
- { spec: ./specs/v1.openapi.yaml, path: /docs/compute/v1/api }

The generated folder

Publier owns the folder a path maps to. It deletes and rewrites it on every build, and it writes a .gitignore containing * into it, so the pages are never committed. The build fails, naming the files, if the folder contains a file Publier did not generate; keep hand-written pages (including the version’s landing page) outside it, for example in /docs/compute/v2/ next to the api/ folder. A spec that fails validation also fails the build, with the validator’s messages. In publier dev, a change to a local spec, or to a file it $refs, regenerates the pages; a new tag’s label and position appear after a restart.

Generating by script

For a custom setup you can still call generateFiles yourself, as the Server-side API section shows. The configuration above is the supported path and needs no script.

Loading a spec

parseOpenApiSpec() accepts a file path, a URL, or the YAML or JSON text. It resolves $refs into other files and URLs, relative to the path or URL you pass. It upgrades Swagger 2.0 specs to OpenAPI 3.0 and validates the result, so an invalid spec stops the build with the validator’s messages. OpenAPI 3.0 and 3.1 specs are kept as written. A circular reference stays a $ref where it loops back.

Code samples

Request examples are generated automatically in six languages: cURL, JavaScript (fetch), Python (requests), Go (net/http), Java (HttpClient), and C#.

Each sample is built from the operation: its security scheme (a placeholder API key, bearer token or basic credentials), its path, query, header and cookie parameters, and its request media type with an example body. The body is your example or examples when the spec has one, else one generated from the schema. Pass the parsed spec to the CodeSamples component so security schemes defined in components apply; APIReference does this for you.

To provide your own, add x-codeSamples to the operation in your spec — the generator uses those instead.

Server-side API

For programmatic access at build time:

import { createOpenAPI } from '@publier/openapi/server';
const openapi = createOpenAPI({ input: ['./openapi.yaml'] });
// Each input may be a file path, a URL, or spec text; all load through parseOpenApiSpec().
const op = await openapi.getOperation('listUsers');
const get = await openapi.getOperationByPath('/users', 'get');
const tag = await openapi.getOperationsByTag('Users');
const nav = await openapi.getNavigation({ slugPrefix: 'api' });

Multi-spec merging just works:

const merged = createOpenAPI({
input: ['./public-api.yaml', './admin-api.yaml'],
});

AsyncAPI

generateFiles() handles OpenAPI paths and webhooks; it does not generate MDX from AsyncAPI channels. integrations.asyncapi does not run a generator today.

The package exports asyncapiSource() for channel page metadata and a navigation tree:

import { asyncapiSource } from '@publier/openapi';
import { readFileSync } from 'node:fs';
import { parse } from 'yaml';
const spec = parse(readFileSync('./asyncapi.yaml', 'utf-8'));
const source = asyncapiSource({ spec, baseUrl: '/async-reference' });
const pages = await source.getPages();
const tree = await source.getPageTree();

This does not write files, register Astro routes, or render page bodies. You must supply your own route and layout. The source correlates operations from the AsyncAPI 3-style top-level operations map with channel references; it does not translate AsyncAPI 2 publish/subscribe operations into that model.

For rendering in your own pages, the existing component exports are:

---
import AsyncChannel from '@publier/openapi/components/async-channel';
import AsyncMessage from '@publier/openapi/components/async-message';
---

AsyncChannel takes channelName, channel, and an operations array of { name, operation, messages } objects, with optional servers. AsyncMessage takes a message. These are rendering building blocks, not an automatic AsyncAPI documentation pipeline.

Components

ComponentPurpose
APIReferenceSingle endpoint — params, body, responses
APIPageFull page layout for an operation
APIPlaygroundInteractive “try it” panel
SchemaViewJSON Schema renderer
CodeSamplesMulti-language request examples
AsyncChannelAsyncAPI channel view
AsyncMessageAsyncAPI message schema

Import from subpath exports:

import APIReference from '@publier/openapi/components/api-reference';

Interactive requests

APIPlayground is a separate component; generated APIReference pages do not automatically include it. Pass the parsed specification so the playground can resolve root security requirements and operation overrides:

---
import APIPlayground from '@publier/openapi/components/api-playground';
import { parse } from 'yaml';
import { readFileSync } from 'node:fs';
const spec = parse(readFileSync('./openapi.yaml', 'utf8'));
const operation = spec.paths['/users'].get;
---
<APIPlayground method="get" path="/users" operation={operation} spec={spec} />

The playground inherits root security unless the operation overrides it; security: [] removes authentication. A selector chooses between alternatives, while schemes in one requirement are applied together. API keys use their declared header or query name. HTTP bearer, HTTP basic, and manually obtained OAuth/OpenID access tokens are supported. The playground does not run an OAuth login flow.

Cookie authentication can opt in to sending existing browser cookies. You cannot type an arbitrary Cookie header; browser cookie, SameSite, and CORS policies still apply. Use a server that permits requests from your docs origin, and include that API origin in your host’s Content Security Policy connect-src directive. Unsupported or unresolved schemes produce a visible error.

Request bodies use the selected media type from requestBody.content. JSON and text are sent as raw text. For application/x-www-form-urlencoded and multipart/form-data, enter a JSON object of scalar fields. Fetch supplies the multipart boundary. File uploads and nested form encoding are not supported. GET and HEAD requests omit the body and do not add a JSON Content-Type.

Existing standalone playgrounds without a spec retain manual bearer and X-API-Key fields. Pass spec to use your API’s declared authentication.