Skip to Content
Vuesho

OpenAPI

Reference pages from OpenAPI documents.

@vuesho/openapi generates reference pages from OpenAPI documents, with schemas, code samples and a playground that sends real requests. The example documents a few httpbin endpoints.

Setup

Install the Package

npm i @vuesho/openapi

Add the Source and Plugin

createOpenAPI() loads the documents, staticSource() returns their pages as a content source under baseDir, and openapiPlugin() renders the pages:

vuesho.config.ts
import { createOpenAPI, openapiPlugin } from "@vuesho/openapi";
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";

const docs = defineDocs();
// A path from the project root, or a URL.
const openapi = createOpenAPI({ input: ["openapi.yaml"] });

export default createSite({
  docs: docs.toSource(),
  api: openapi.staticSource({ baseDir: "api" }), 
}).plugins(recommendedPreset(), openapiPlugin());

Run vuesho dev and open a page under /api, like /api/createNote for the operation with the operationId createNote.

Name the Folder

The pages are in an api folder in the sidebar. To give the folder a title, add a meta file to the content folder:

content/api/meta.json
{ "title": "API Reference" }

CORS

The playground sends requests from the browser, so it reaches only an API whose CORS headers allow your site's origin. For other APIs, turn on the proxy.

Pages

Each operation and webhook has a page, named after its operationId, with its method as a badge in the sidebar. The generated pages are in search and llms.txt, like your other pages. per and groupBy arrange the pages into other files and folders, as the tabs show for the example:

echoQuery.md
createNote.md
getStatus.md
checkBearer.md

per: "file" puts each document on one page. groupBy groups the pages in folders, and meta: true orders them:

vuesho.config.ts
openapi.staticSource({
  baseDir: "api",
  groupBy: "tag",
  // Generates the meta files, which order the pages as the document does.
  meta: true,
});

A tag's folder takes its title from x-displayName, or else from an OpenAPI 3.2 tag's summary. An OpenAPI 3.2 tag with a parent nests in its parent's folder. Operations without a tag go in an unknown folder:

openapi.yaml
tags:
  - name: store
    x-displayName: Store
  - name: products
    parent: store

badges: false on openapiPlugin() removes the method badges and the strikethrough on deprecated operations from the sidebar.

Documents

Multiple Documents

A document's ID is its file name, or the last segment of its URL, without the extension. To choose the IDs, pass a record. Its values can also be document objects, or functions that return a document:

vuesho.config.ts
const openapi = createOpenAPI({
  input: {
    store: "openapi/store.yaml",
    billing: "https://api.example.com/openapi.json",
  },
});

To put each document in a separate folder, prefix the file name with this.id in name:

vuesho.config.ts
openapi.staticSource({
  baseDir: "api",
  per: "operation",
  name(output) {
    const slug = output.info.title.toLowerCase().replaceAll(" ", "-");
    return `${this.id}/${slug}`; 
  },
});

Trusted Documents Only

The server reads the local files and the URLs that a document references with $ref, so load only documents you trust.

input as a Function

input can be a function, called once with onRead. Call onRead with each local file it reads, like a config that lists the documents, so the built server gets those files too:

vuesho.config.ts
import { readFileSync } from "node:fs";

const openapi = createOpenAPI({
  input(onRead) {
    onRead("api-config.json");
    const config: { documents: string[] } = JSON.parse(readFileSync("api-config.json", "utf8"));
    return config.documents;
  },
});

Live Updates

staticSource() reads the documents when the site starts, so restart vuesho dev after you edit one.

dynamicSource() reads the documents on the server, renders the pages on request, and reads the documents again after staleTime, like any dynamic source:

vuesho.config.ts
createSite({
  docs: docs.toSource(),
  api: openapi.staticSource({ baseDir: "api" }), 
  api: openapi.dynamicSource({ baseDir: "api", staleTime: 60_000 }), 
});

Deploy a local document with the server, since dynamicSource() reads it there.

Playground

An operation's playground sends requests from the browser, with fields for the parameters, the body and the credentials of its security schemes. Configure it with the playground option of createOpenAPIPage(), or turn it off with playground: { enabled: false }.

Proxy

With proxy on openapiPlugin(), the playground sends its requests through /_openapi/proxy, a route on your site. The route renders on request, so the site needs a server:

vuesho.config.ts
openapiPlugin({
  proxy: { allowedOrigins: ["https://api.example.com"] },
});

With proxy: true, the proxy reaches only the documents' servers, and strips cookies. allowedOrigins: "public" allows any host outside private networks.

Cookies

With a list of allowedOrigins, the proxy forwards your site's cookies to those origins and returns their Set-Cookie headers, so list only origins you trust.

A static site can run the proxy elsewhere, like in a serverless function, with createProxy():

api/proxy.ts
import { createOpenAPI, createProxy } from "@vuesho/openapi";

const proxy = createProxy({ openapi: createOpenAPI({ input: ["openapi.yaml"] }) });

export default { fetch: proxy.handle };
vuesho.config.ts
openapiPlugin({ proxy: { url: "/api/proxy" } });

OAuth

An OAuth 2.0 flow that redirects returns to the page that started it, so the provider must allow the URL of every page. oauth: true adds one callback page instead, /_openapi/oauth.html, which you register with the provider. It works under a Content Security Policy of script-src 'self':

vuesho.config.ts
openapiPlugin({ oauth: true });

Authorization

authProviders replaces a security scheme's fields. on takes a scheme's ID, or a function that matches schemes. render is a component that receives the row components, like Value, which edits the value:

src/BearerRows.vue
<script setup lang="ts">
import type { AuthRenderProps } from "@vuesho/openapi/playground";

defineProps<AuthRenderProps>();
</script>

<template>
  <component :is="Value" name="Authorization" type="header" start="Bearer" />
</template>
src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import BearerRows from "./BearerRows.vue";

export const OpenAPIPage = createOpenAPIPage({
  playground: { authProviders: [{ on: "bearer", render: BearerRows }] }, 
});

For a sign-in that leaves the page, useAuthRedirect() from @vuesho/openapi/playground redirects the reader, and reads the result when they come back.

Custom Fields

renderParameterField and renderBodyField replace a parameter's input or the body's. Return undefined to keep the default input, or call renderDefault() with another schema:

src/api-page.ts
import { h } from "vue";
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import ColorField from "./ColorField.vue";

export const OpenAPIPage = createOpenAPIPage({
  playground: {
    renderParameterField(field, param, { renderDefault }) {
      if (param.name === "region") return renderDefault({ type: "string", enum: ["eu", "us"] });
      if (param.name === "color") return h(ColorField, { field });
    },
  },
});

A custom input reads and writes its value with Custom.useController():

src/ColorField.vue
<script setup lang="ts">
import { Custom } from "@vuesho/openapi/ui/playground/client";

const props = defineProps<{ field: (string | number)[] }>();
const { value, setValue } = Custom.useController(props.field, { defaultValue: "#000000" });
</script>

<template>
  <input type="color" :value="value" @input="setValue(($event.target as HTMLInputElement).value)" />
</template>

Scalar API Client

withScalar() replaces the playground with the Scalar API Client. The Scalar client sends the requests itself, so proxy, oauth and playground don't apply to it:

npm i @scalar/api-client @scalar/workspace-store

With pnpm, the install stops on the build script of vue-demi, which Scalar's dependencies bring. Its files already target Vue 3, so either answer works: allowBuilds: { vue-demi: false } in pnpm-workspace.yaml skips the script, and true runs it.

src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import { withScalar } from "@vuesho/openapi/ui/scalar";

export const OpenAPIPage = createOpenAPIPage(withScalar({ showResponseSchema: false }));

The client is about 1 MB of gzipped JavaScript, which loads when a playground first renders, and its stylesheet adds about 30 kB of CSS to each API page.

Customization

Create the page component with your options in createOpenAPIPage(), and set it as the openapi page body in your theme:

src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";

export const OpenAPIPage = createOpenAPIPage({
  // Shows only the example response and the TypeScript definitions.
  showResponseSchema: false,
  schemaUI: { showExample: true },
});
src/theme.ts
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";
import type app from "../vuesho.config";

export default defineTheme<typeof app>({
  extends: defaultTheme,
  bodies: { openapi: () => import("./api-page").then((mod) => mod.OpenAPIPage) }, 
});

To use <OpenAPIPage> in Markdown with the same options, re-export it from src/components/content/:

src/components/content/OpenAPIPage.ts
export { OpenAPIPage as default } from "../../api-page";

On a site with several sources, give it source, the key in createSite() of the OpenAPI source.

Code Samples

An operation has samples in cURL, JavaScript, Go, Python, Java, C#, Ruby and Rust. codeUsages changes the languages for every operation:

src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import { createCodeUsageGeneratorRegistry, registerDefault } from "@vuesho/openapi/requests";

const codeUsages = createCodeUsageGeneratorRegistry();
registerDefault(codeUsages);
codeUsages.add("sdk", {
  label: "SDK",
  lang: "ts",
  generate: (data) => `await client.request(${JSON.stringify(data.url)});`,
});

export const OpenAPIPage = createOpenAPIPage({ codeUsages });

To change one operation's samples, use generateCodeSamples, or add x-codeSamples to the operation in the document:

openapi.yaml
paths:
  /notes:
    post:
      x-codeSamples:
        - lang: ts
          label: SDK
          source: 'await client.notes.create({ text: "Hello" });'

Components

components replaces parts of the page. A layout receives the parts as named slots, so it can reorder them:

src/OperationLayout.vue
<script setup lang="ts">
import type { OperationLayoutProps } from "@vuesho/openapi/client";

defineProps<OperationLayoutProps>();
</script>

<template>
  <div class="flex flex-col gap-4">
    <slot name="header" />
    <slot name="description" />
    <slot name="api-playground" />
    <slot name="auth-schemes" />
    <slot name="parameters" />
    <slot name="body" />
    <slot name="responses" />
    <slot name="api-example" />
    <slot name="callbacks" />
  </div>
</template>
src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import OperationLayout from "./OperationLayout.vue";

export const OpenAPIPage = createOpenAPIPage({ components: { OperationLayout } });

To change a part freely, copy it into src/ui/@vuesho/openapi/ with vuesho add. --from @vuesho/api-docs copies the parts that every API integration shares, like the schemas and the playground fields:

npx vuesho add operation --from @vuesho/openapi
src/api-page.ts
import { createOpenAPIPage } from "@vuesho/openapi/ui";
import { Operation } from "./ui/@vuesho/openapi/operation";

export const OpenAPIPage = createOpenAPIPage({ components: { Operation } });

Headless Usage

To build the page with a custom UI, use the headless entries: @vuesho/openapi/client for the document and its operations, @vuesho/openapi/playground for requests and credentials, @vuesho/openapi/requests for code samples, and @vuesho/api-docs/json-schema for schemas.

Translations

The generated pages are in each of your site's languages. The UI has language packs for ja, zh-CN and zh-TW, and ui.translations replaces any of its texts:

vuesho.config.ts
createSite(sources, { i18n }).config({
  site: { languages: { cn: { lang: "zh-CN" } } },
  ui: { translations: { cn: { "Send(playground)": "发送请求" } } }, 
});

Options

staticSource() and dynamicSource()

Prop

Type

per: "tag" and per: "file" take the same options except groupBy. per: "custom" takes toPages() instead, which creates the pages.

openapiPlugin()

Prop

Type

proxy's options, which createProxy() takes too:

Prop

Type

createOpenAPIPage()

Prop

Type

playground's options:

Prop

Type

The parts that components replaces:

Prop

Type

<OpenAPIPage>

Prop

Type