diff --git a/.changeset/ten-carpets-cover.md b/.changeset/ten-carpets-cover.md new file mode 100644 index 000000000..643baa19c --- /dev/null +++ b/.changeset/ten-carpets-cover.md @@ -0,0 +1,5 @@ +--- +'@gitbook/react-openapi': patch +--- + +Render mandatory headers in code sample diff --git a/packages/react-openapi/src/OpenAPICodeSample.tsx b/packages/react-openapi/src/OpenAPICodeSample.tsx index ae0d4b552..d26a6f3b8 100644 --- a/packages/react-openapi/src/OpenAPICodeSample.tsx +++ b/packages/react-openapi/src/OpenAPICodeSample.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import { CodeSampleInput, codeSampleGenerators } from './code-samples'; import { OpenAPIOperationData, toJSON } from './fetchOpenAPIOperation'; -import { generateMediaTypeExample } from './generateSchemaExample'; +import { generateMediaTypeExample, generateSchemaExample } from './generateSchemaExample'; import { InteractiveSection } from './InteractiveSection'; import { getServersURL } from './OpenAPIServerURL'; import { ScalarApiButton } from './ScalarApiButton'; @@ -19,6 +19,21 @@ export function OpenAPICodeSample(props: { }) { const { data, context } = props; + const requiredHeaders = data.operation.parameters + ?.map(noReference) + .filter((param) => param.in === 'header' && param.required); + + const headersObject: { [k: string]: string } = {}; + requiredHeaders?.forEach((header) => { + const example = header.schema + ? generateSchemaExample(noReference(header.schema)) + : undefined; + if (example !== undefined) { + headersObject[header.name] = + typeof example !== 'string' ? JSON.stringify(example) : example; + } + }); + const requestBody = noReference(data.operation.requestBody); const requestBodyContent = requestBody ? Object.entries(requestBody.content)[0] : undefined; @@ -30,6 +45,7 @@ export function OpenAPICodeSample(props: { : undefined, headers: { ...getSecurityHeaders(data.securities), + ...headersObject, ...(requestBodyContent ? { 'Content-Type': requestBodyContent[0],