# Fumadocs (Framework Mode, TanStack Start): OpenAPI
URL: /zh-TW/docs/tanstack-start/integrations/openapi
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/openapi/index.zh-TW.mdx

根據 OpenAPI schema 產生文件。

## 設定 [#setup]

請安裝所需的套件。

```npm
npm i fumadocs-openapi shiki
```

### 產生樣式 [#generate-styles]

請加入下面這一行：

```css title="Tailwind CSS"
@import 'tailwindcss';
@import 'fumadocs-ui/css/neutral.css';
@import 'fumadocs-ui/css/preset.css';
/* [!code ++] */
@import 'fumadocs-openapi/css/preset.css';
```

### 設定外掛 [#configure-plugin]

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

```ts tab="lib/openapi.ts"
import { createOpenAPI } from 'fumadocs-openapi/server';

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

```tsx tab="components/api-page.tsx"
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';

export const OpenAPIPage = createOpenAPIPage();
```

如需了解可用選項，請參閱 [`createOpenAPI()`](/docs/tanstack-start/integrations/openapi/server) 與 [`createOpenAPIPage()`](/docs/tanstack-start/integrations/openapi/api-page)。

### 產生頁面 [#generate-pages]

將 `staticSource()` 傳入您的 [`loader()`](/docs/headless/source-api/source)，即可產生頁面，而不必實際寫入檔案。

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

```ts tab="src/lib/source.ts"
import { loader } from 'fumadocs-core/source';
import { defineDocs } from 'fumadocs-mdx/macro'; // [!code --]
// [!code ++:2]
import { docs } from '@/lib/collections';
import { openapi } from '@/lib/openapi';

// [!code --:6]
export const docs = defineDocs({
  dir: 'content/docs',
  docs: {
    async: true,
  },
});

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

```ts tab="src/lib/collections.ts"
import { defineDocs } from 'fumadocs-mdx/macro';

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

`staticSource()` 預設會為每個 operation 產生一個頁面。如需自訂，請參閱[產生頁面](/docs/tanstack-start/integrations/openapi/generate-files)。

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

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

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

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

在您的文件頁面中，使用 `<OpenAPIPage />` 算繪 OpenAPI 頁面：

```tsx title="src/routes/docs/$.tsx"
import { docs, source } from '@/lib/source'; // [!code --]
// [!code ++:3]
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(); // [!code highlight]
    return data;
  },
});

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

    // [!code ++:9]
    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 }; // [!code highlight]
  });

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

  return (
    <DocsLayout {...baseOptions()} tree={data.pageTree}>
      {/* [!code ++:8] */}
      {data.type === 'openapi' && (
        <DocsPage full>
          <DocsTitle>{data.title}</DocsTitle>
          <DocsBody>
            <OpenAPIPage {...data.props} />
          </DocsBody>
        </DocsPage>
      )}
      <Suspense>
        {/* [!code highlight] */}
        {data.type === 'docs' && <Content path={data.path} />}
      </Suspense>
    </DocsLayout>
  );
}
```

<Callout type="warn" title="請確認已完成遷移！">
繼續之前，請先執行型別檢查：

```npm
npm run types:check
```
</Callout>

若想改為將 MDX 檔案寫入內容目錄，請參閱 [MDX 檔案](/docs/tanstack-start/integrations/openapi/generate-files#mdx-files)。

## 功能 [#features]

官方 OpenAPI 整合支援：

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

### 示範 [#demo]

[查看示範](/docs/openapi)。