From d7948e34b2b73e53867eedad5f00efa7813e3267 Mon Sep 17 00:00:00 2001 From: spastorelli Date: Thu, 18 Sep 2025 18:40:24 +0200 Subject: [PATCH] Fix OpenAPI response showing as JSON instead of YAML (#3669) --- .changeset/two-coats-trade.md | 5 +++++ packages/react-openapi/src/OpenAPIExample.tsx | 16 ++++++++++++---- packages/react-openapi/src/util/example.tsx | 4 ++++ 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 .changeset/two-coats-trade.md diff --git a/.changeset/two-coats-trade.md b/.changeset/two-coats-trade.md new file mode 100644 index 000000000..b6e879697 --- /dev/null +++ b/.changeset/two-coats-trade.md @@ -0,0 +1,5 @@ +--- +"@gitbook/react-openapi": patch +--- + +Fix OpenAPI response showing as JSON instead of YAML when it should diff --git a/packages/react-openapi/src/OpenAPIExample.tsx b/packages/react-openapi/src/OpenAPIExample.tsx index 7f9328d6f..9d91e6feb 100644 --- a/packages/react-openapi/src/OpenAPIExample.tsx +++ b/packages/react-openapi/src/OpenAPIExample.tsx @@ -1,3 +1,5 @@ +import yaml from 'js-yaml'; + import type { OpenAPIV3 } from '@gitbook/openapi-parser'; import type { OpenAPIContext, OpenAPIUniversalContext } from './context'; import { json2xml } from './json2xml'; @@ -13,7 +15,7 @@ export function OpenAPIExample(props: { syntax: string; }) { const { example, context, syntax } = props; - const code = stringifyExample({ example, xml: syntax === 'xml' }); + const code = stringifyExample({ example, syntax }); if (code === null) { return ; @@ -22,8 +24,10 @@ export function OpenAPIExample(props: { return context.renderCodeBlock({ code, syntax }); } -function stringifyExample(args: { example: OpenAPIV3.ExampleObject; xml: boolean }): string | null { - const { example, xml } = args; +function stringifyExample(args: { example: OpenAPIV3.ExampleObject; syntax: string }): + | string + | null { + const { example, syntax } = args; if (!example.value) { return null; @@ -33,10 +37,14 @@ function stringifyExample(args: { example: OpenAPIV3.ExampleObject; xml: boolean return example.value; } - if (xml) { + if (syntax === 'xml') { return json2xml(example.value); } + if (syntax === 'yaml') { + return yaml.dump(example.value).replace(/'/g, '').replace(/\\n/g, '\n'); + } + return stringifyOpenAPI(example.value, null, 2); } diff --git a/packages/react-openapi/src/util/example.tsx b/packages/react-openapi/src/util/example.tsx index 95b295e58..9d8d2dd28 100644 --- a/packages/react-openapi/src/util/example.tsx +++ b/packages/react-openapi/src/util/example.tsx @@ -121,6 +121,10 @@ function getSyntaxFromMediaType(mediaType: string): string { return 'json'; } + if (mediaType.includes('yaml')) { + return 'yaml'; + } + if (mediaType === 'application/xml') { return 'xml'; }