# Fumadocs (Framework Mode, Next.js): createOpenAPIPage()
URL: /docs/next/integrations/openapi/api-page
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/openapi/api-page.mdx

The component for rendering OpenAPI docs content

## Overview [#overview]

Fumadocs OpenAPI uses a `<OpenAPIPage />` component to render page contents, it should be a client component.

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

export const OpenAPIPage = createOpenAPIPage({
  // config
});
```

### Generate Code Usages [#generate-code-usages]

Generate code usage examples for each API endpoint.

```tsx title="components/api-page.tsx" twoslash
'use client';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
import {
  createCodeUsageGeneratorRegistry,
  type CodeUsageGenerator,
} from 'fumadocs-openapi/requests/generators';
import { registerDefault } from 'fumadocs-openapi/requests/generators/all';

const codeUsages = createCodeUsageGeneratorRegistry();

// include defaults
registerDefault(codeUsages);

// add custom generators
codeUsages.add('custom-id', {
  label: 'My Example',
  lang: 'js',
  generate(data, { mediaAdapters }) {
    // request data
    console.log(data);

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

export const OpenAPIPage = createOpenAPIPage({
  // [!code ++]
  codeUsages,
});
```

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

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

### Internationalization [#internationalization]

Assuming you have configured [Internationalization](/docs/next/internationalization) at UI level:

```tsx title="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())
  // [!code ++]
  .extend(openapiTranslations())
  .add({
    cn: {
      displayName: 'Chinese',
      // [!code ++]
      'Body(playground)': '請求正文',
    },
  });
```

See [Translations](/docs/ui/translations) for more details.

## Media Adapters [#media-adapters]

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

- Converting value into `fetch()` body compatible with corresponding media type.
- Generate code example based on different programming language/tool.

Request bodies of other media types are read-only: they are left out of code usages, and cannot be sent from the playground.

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

const mediaAdapters: Record<string, MediaAdapter> = {
  // example: custom `application/json
  'application/json': {
    encode(data) {
      return JSON.stringify(data.body);
    },
    // returns code that inits a `body` variable, used for request body
    generateExample(data, ctx) {
      if (ctx.lang === 'js') {
        return `const body = "hello world"`;
      }

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

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

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

export const OpenAPIPage = createOpenAPIPage({
  // [!code ++]
  mediaAdapters,
});
```

## Authorization [#authorization]

Auth providers handle the security schemes of the playground: the rows of their values, and how values are sent.

```tsx title="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: [
      {
        // a scheme ID or a function, every scheme when omitted
        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>
  );
}
```

| Option      | Is                                                                       |
| ----------- | ------------------------------------------------------------------------ |
| `on`        | the security schemes it handles                                          |
| `render`    | its rows, from `Value` (an input of the value) and `Panel` (a panel)     |
| `onRequest` | write the value into request data, for requests and code usages (masked) |

Define providers outside of components, the auth fields are created again when they change.

Rows and panels hold their own state, `Custom.useController(field.fieldName)` reads and writes the value. It is kept per scheme while the tab is open. Tokens are sent with their scheme, like `Bearer <token>`.

<Accordions>
<Accordion title="Sign-ins leaving the page">
Leave the page with the function from `useAuthRedirect()`. When the page loads again, the playground reopens, and the rows get the data back in `onReturn`.

```tsx
import { Custom } from 'fumadocs-openapi/ui/playground/client';
import {
  type AuthPanelProps,
  type AuthRenderProps,
  useAuthRedirect,
} from 'fumadocs-openapi/playground';

function Rows({ field, Value, Panel }: AuthRenderProps) {
  const { setValue } = Custom.useController(field.fieldName);

  useAuthRedirect(field, (url, state) => {
    if (url.searchParams.get('state') === state)
      setValue(url.searchParams.get('token')!);
  });

  return (
    <>
      <Value name="Authorization" type="header" start="Bearer" />
      <Panel title="Sign in" component={SignIn} />
    </>
  );
}

function SignIn({ field }: AuthPanelProps) {
  const redirect = useAuthRedirect(field);

  return (
    <button
      onClick={() => {
        const state = crypto.randomUUID();
        redirect(`https://auth.example.com/login?state=${state}`, state);
      }}
    >
      Sign in
    </button>
  );
}
```
</Accordion>
</Accordions>

## Customise UI [#customise-ui]

For customisations beyond the available options, you can install the UI into your codebase with [Fumadocs CLI](/docs/cli).

### Full UI [#full-ui]

The entire UI of API pages, built on [the headless layer](/docs/next/integrations/openapi/headless).

```npm
npx @fumadocs/cli add openapi/page
```

It installs `<OpenAPIPage />` itself, so `components/api-page.tsx` is no longer needed. Update the imports of `<OpenAPIPage />`:

```tsx
import { OpenAPIPage } from '@/components/api-page'; // [!code --]
import { OpenAPIPage } from '@/components/openapi/page'; // [!code ++]
```

### API Playground [#api-playground]

The UI of the playground, its state comes from [`usePlayground()`](/docs/next/integrations/openapi/headless#playground).

```npm
npx @fumadocs/cli add openapi/playground
```

```tsx title="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]

The UI of operations and webhooks.

```npm
npx @fumadocs/cli add openapi/operation
```

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

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

### Schema UI [#schema-ui]

The UI of JSON schemas, its state comes from [`<SchemaUIProvider />`](/docs/next/integrations/openapi/headless#schema-ui).

```npm
npx @fumadocs/cli add api-docs/schema
```

```tsx title="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,
  },
});
```