Fumadocs

<APIPage />

用于渲染 OpenAPI 文档内容的组件

概览

🌐 Overview

Fumadocs OpenAPI 使用 <APIPage /> 组件来渲染页面内容。

🌐 Fumadocs OpenAPI uses a <APIPage /> component to render page contents.

在自定义时,选项会被分为服务器端和客户端配置。

🌐 When customising it, the options are split into server/client configs.

import { openapi } from '@/lib/openapi';
import { createAPIPage } from 'fumadocs-openapi/ui';
import client from './api-page.client';

export const APIPage = createAPIPage(openapi, {
  client,
  // server config
});

强烈建议安装类型包以进行高级自定义:

🌐 Installing the types packages is highly recommended for advanced customisations:

npm install openapi-types json-schema-typed -D

它给你提供了更高级别的类型安全性。

🌐 It gives you a higher level of type-safety.

生成代码示例

🌐 Generate Code Samples

为每个 API 端点生成自定义代码示例。

🌐 Generate custom code samples for each API endpoint.

import { openapi } from '@/lib/openapi';
import { createAPIPage } from 'fumadocs-openapi/ui';

export const APIPage = createAPIPage(openapi, {
  generateCodeSamples(endpoint) {
    return [
      {
        id: 'js',
        lang: 'js',
        label: 'JavaScript SDK',
        source: "console.log('hello')",
      },
      // or to disable the default code samples
      // set `source: false`
      {
        id: 'curl',
        lang: 'bash',
        source: false,
      },
    ];
  },
});

此外,你还可以通过 OpenAPI 架构指定代码示例。

🌐 In addition, you can also specify code samples via OpenAPI schema.

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

媒体适配器

🌐 Media Adapters

你可以创建一个媒体适配器来支持 API 页面中的其他媒体类型,媒体适配器实现了:

🌐 You can create a media adapter to support other media types in API pages, a media adapter implements:

  • 将值转换为与相应媒体类型兼容的 fetch() 实体。
  • 根据不同的编程语言/工具生成代码示例。

将你的媒体适配器放在一个单独的文件中。

🌐 Put your media adapters in a separate file.

lib/media-adapters.ts
import type { MediaAdapter } from 'fumadocs-openapi';

export const : <string, MediaAdapter> = {
  // example: custom `application/json
  'application/json': {
    () {
      return .(.);
    },
    // returns code that inits a `body` variable, used for request 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")`;
      }
    },
  },
};

将适配器传递给客户端和服务器配置。

🌐 Pass the adapter to both client & server configs.

import { openapi } from '@/lib/openapi';
import { createAPIPage } from 'fumadocs-openapi/ui';
import { mediaAdapters } from '@/lib/media-adapters';
import client from './api-page.client';

export const APIPage = createAPIPage(openapi, {
  client,
  mediaAdapters,
});

Last updated on

On this page