Fumadocs rebuilt on Hamur, the original is fumadocs.dev
跳至內容
Fumadocs

OpenAPI

根據 OpenAPI schema 產生文件。

從 OpenAPI 文件產生 API 參考頁面,並提供可直接傳送請求的互動測試區。請參閱示範。

設定

請安裝所需的套件。

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()。它會直接產生頁面,不會寫入任何檔案。

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

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

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 頁面:

app/docs/[[...slug]]/page.tsx
import { OpenAPIPage } from '@/components/api-page'; 

export default async function Page(props: PageProps<'/docs/[[...slug]]'>) {
  const params = await props.params;
  const page = source.getPage(params.slug);
  if (!page) notFound();

  if (page.type === 'openapi') {
    return (
      <DocsPage full>
        <DocsTitle>{page.data.title}</DocsTitle>
        <DocsBody>
          <OpenAPIPage {...page.data.getOpenAPIPageProps()} />
        </DocsBody>
      </DocsPage>
    );
  }

  // ...
}

請確認已完成遷移!

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

npm run types:check

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

How is this guide?

最後更新於