跳至內容
Fumadocs

OpenAPI

根據 OpenAPI schema 產生文件。

設定

請安裝所需的套件。

npm i fumadocs-openapi shiki

產生樣式

請加入下面這一行:

Tailwind CSS
@import 'tailwindcss';
@import 'fumadocs-ui/css/neutral.css';
@import 'fumadocs-ui/css/preset.css';
@import 'fumadocs-openapi/css/preset.css';

設定外掛

建立 OpenAPI 伺服器實例及 <OpenAPIPage /> 元件。

import { createOpenAPI } from 'fumadocs-openapi/server';

// 注意:這是伺服器端 API
export const openapi = createOpenAPI({
  // OpenAPI schema,也可以改為提供外部 URL。
  input: ['./openapi.json'],
});

如需了解可用選項,請參閱 createOpenAPI() 與 createOpenAPIPage()。

產生頁面

將 staticSource() 傳入您的 loader(),即可產生頁面,而不必實際寫入檔案。

由於 staticSource() 會讀取檔案,source.ts 將變成僅限伺服器端使用。請將 docs 移至 collections.ts,讓用戶端程式碼可以匯入。

import { loader } from 'fumadocs-core/source';
import { defineDocs } from 'fumadocs-mdx/macro'; 
import { docs } from '@/lib/collections';
import { openapi } from '@/lib/openapi';

export const docs = defineDocs({
  dir: 'content/docs',
  docs: {
    async: true,
  },
});

// 由於 `staticSource()` 會讀取檔案,現在僅限伺服器端使用
export const source = loader(
  {
    docs: docs.toFumadocsSource(),
    openapi: await openapi.staticSource({
      baseDir: 'openapi',
    }),
  },
  {
    baseUrl: '/docs',
    // 選用:為頁面樹中的每個頁面項目加上徽章
    plugins: [openapi.loaderPlugin()],
  },
);

staticSource() 預設會為每個 operation 產生一個頁面。如需自訂,請參閱產生頁面。

source 的頁面現在有 docs 與 openapi 兩種類型。 請更新所有使用到 source 的地方,例如為 LLM 回傳文字的程式碼:

import { llms } from 'fumadocs-core/source';
import { source } from '@/lib/source';

export const docsLlms = llms(source, {
  renderPage: (page) => {
    if (page.type === 'openapi') {
      // 例如:回傳序列化為字串的 OpenAPI schema
      return JSON.stringify(page.data.getSchema().bundled, null, 2);
    }

    // 以下為您原本的流程……
  },
});

在您的文件頁面中,使用 <OpenAPIPage /> 算繪 OpenAPI 頁面:

src/routes/docs/$.tsx
import { docs, source } from '@/lib/source'; 
import { docs } from '@/lib/collections';
import { source } from '@/lib/source';
import { OpenAPIPage } from '@/components/api-page';

export const Route = createFileRoute('/docs/$')({
  component: Page,
  loader: async ({ params }) => {
    const slugs = params._splat?.split('/') ?? [];
    const data = await serverLoader({ data: slugs });
    if (data.type === 'docs') await docs.getPage(data.path)?.preload(); 
    return data;
  },
});

const serverLoader = createServerFn({
  method: 'GET',
})
  .validator((slugs: string[]) => slugs)
  .handler(async ({ data: slugs }) => {
    const page = source.getPage(slugs);
    if (!page) throw notFound();

    const pageTree = await source.serializePageTree(source.getPageTree());
    if (page.type === 'openapi') {
      return {
        type: 'openapi',
        title: page.data.title,
        props: page.data.getOpenAPIPageProps(),
        pageTree,
      };
    }

    return { type: 'docs', path: page.path, pageTree }; 
  });

function Page() {
  const data = useFumadocsLoader(Route.useLoaderData());

  return (
    <DocsLayout {...baseOptions()} tree={data.pageTree}>
      {data.type === 'openapi' && (
        <DocsPage full>
          <DocsTitle>{data.title}</DocsTitle>
          <DocsBody>
            <OpenAPIPage {...data.props} />
          </DocsBody>
        </DocsPage>
      )}
      <Suspense>
        {data.type === 'docs' && <Content path={data.path} />}
      </Suspense>
    </DocsLayout>
  );
}

請確認已完成遷移!

繼續之前,請先執行型別檢查:

npm run types:check

若想改為將 MDX 檔案寫入內容目錄,請參閱 MDX 檔案。

功能

官方 OpenAPI 整合支援:

  • 基本的 API 端點資訊
  • API 互動測試區
  • 傳送請求的範例程式碼 (支援多種程式語言)
  • 回應範例與 TypeScript 型別定義
  • 根據 schema 產生的請求參數與 body

示範

查看示範。

How is this guide?

最後更新於