跳至內容
Fumadocs

createOpenAPIPage()

用於算繪 OpenAPI 文件內容的元件

概覽

Fumadocs OpenAPI 使用 <OpenAPIPage /> 元件來算繪頁面內容,此元件應為用戶端元件。

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

export const OpenAPIPage = createOpenAPIPage({
  // 設定
});

產生程式碼使用範例

為每個 API 端點產生程式碼使用範例。

components/api-page.tsx
'use client';
import {  } from 'fumadocs-openapi/ui';
import {
  ,
  type ,
} from 'fumadocs-openapi/requests/generators';
import {  } from 'fumadocs-openapi/requests/generators/all';

const  = ();

// 加入預設產生器
();

// 新增自訂產生器
.('custom-id', {
  : 'My Example',
  : 'js',
  (, {  }) {
    // 請求資料
    .();

    return 'const response = "hello world";';
  },
});

export const  = ({
  ,
});

此外,您也可以透過 OpenAPI schema 指定程式碼範例。

paths:
  /plants:
    get:
      x-codeSamples:
        - lang: js
          label: JavaScript SDK
          source: |
            const planter = require('planter');
            planter.list({ unwatered: true });

國際化

假設您已在 UI 層級設定好國際化:

layout.shared.tsx
import { defineI18n } from 'fumadocs-core/i18n';
import { uiTranslations } from 'fumadocs-ui/i18n';
import { openapiTranslations } from 'fumadocs-openapi/i18n';

const i18n = defineI18n({
  languages: ['en', 'cn'],
  defaultLanguage: 'en',
});

export const translations = i18n
  .translations()
  .extend(uiTranslations())
  .extend(openapiTranslations())
  .add({
    cn: {
      displayName: 'Chinese',
      'Body(playground)': '請求正文',
    },
  });

詳情請參閱翻譯。

媒體轉接器

您可以建立媒體轉接器,讓 API 頁面支援其他媒體類型。媒體轉接器需實作以下功能:

  • 將值轉換為對應媒體類型適用的 fetch() body。
  • 針對不同的程式語言/工具產生程式碼範例。

其他媒體類型的請求 body 為唯讀:不會出現在程式碼使用範例中,也無法在互動測試區中送出。

components/api-page.tsx
'use client';
import {  } from 'fumadocs-openapi/ui';
import type { MediaAdapter } from 'fumadocs-openapi';

const : <string, MediaAdapter> = {
  // 範例:自訂 `application/json
  'application/json': {
    () {
      return .(.);
    },
    // 回傳用來初始化 `body` 變數的程式碼,作為請求 body 使用
    (, ) {
      if (. === 'js') {
        return `const body = "hello world"`;
      }

      if (. === 'python') {
        return `body = "hello world"`;
      }

      if (. === 'go' && 'addImport' in ) {
        .('strings');

        return `body := strings.NewReader("hello world")`;
      }
    },
  },
};

export const  = ({
  ,
});

授權

驗證提供者 (auth provider) 負責處理互動測試區的安全性方案,包括其值的輸入列,以及這些值的傳送方式。

components/api-page.tsx
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
import { Custom } from 'fumadocs-openapi/ui/playground/client';
import type { AuthPanelProps } from 'fumadocs-openapi/playground';

export const OpenAPIPage = createOpenAPIPage({
  playground: {
    authProviders: [
      {
        // 可為 scheme ID 或函式;省略時套用至所有 scheme
        on: 'my-auth',
        render: ({ Value, Panel }) => (
          <>
            <Value name="Authorization" type="header" start="Bearer" />
            <Panel title="Sign in" component={SignIn} />
          </>
        ),
      },
    ],
  },
});

function SignIn({ field, close }: AuthPanelProps) {
  const { setValue } = Custom.useController(field.fieldName);

  return (
    <button
      onClick={async () => {
        const res = await fetch('/api/token');
        setValue(await res.text());
        close();
      }}
    >
      Sign in
    </button>
  );
}
選項說明
on它所處理的安全性方案
render它的各列,由 Value (值的輸入欄位) 與 Panel (面板) 組成
onRequest將值寫入請求資料,供請求與程式碼使用範例使用 (會遮蔽顯示)

請在元件外部定義 provider,因為 provider 一旦變更,驗證欄位就會重新建立。

各列與面板各自保有自己的狀態,可透過 Custom.useController(field.fieldName) 讀寫該值。在頁籤開啟期間,值會依方案分別保存。權杖會連同其方案一併送出,例如 Bearer <token>。

自訂 UI

若現有選項無法滿足您的自訂需求,您可以使用 Fumadocs CLI 將 UI 安裝到自己的程式碼庫中。

完整 UI

API 頁面的完整 UI,建構於無頭式層之上。

npx @fumadocs/cli add openapi/page

它會直接安裝 <OpenAPIPage />,因此不再需要 components/api-page.tsx。請更新 <OpenAPIPage /> 的匯入路徑:

import { OpenAPIPage } from '@/components/api-page'; 
import { OpenAPIPage } from '@/components/openapi/page'; 

API 互動測試區

互動測試區的 UI,其狀態由 usePlayground() 提供。

npx @fumadocs/cli add openapi/playground
components/api-page.tsx
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
import PlaygroundClient from '@/components/openapi/playground';

export const OpenAPIPage = createOpenAPIPage({
  playground: {
    render: () => <PlaygroundClient />,
  },
});

Operation

operation 與 webhook 的 UI。

npx @fumadocs/cli add openapi/operation
components/api-page.tsx
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
import { Operation } from '@/components/openapi/operation';

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

結構描述 UI

用於呈現 JSON schema 的 UI,其狀態來自 <SchemaUIProvider />。

npx @fumadocs/cli add api-docs/schema
components/api-page.tsx
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
import { Schema } from '@/components/api/schema';

export const OpenAPIPage = createOpenAPIPage({
  components: {
    SchemaUI: Schema,
  },
});

How is this guide?

最後更新於