What is the code samples extension?

Many API documentation providers will provide code snippets in multiple languages to help developers understand how to use the API. However these snippets may not correspond to a usage snippet from an existing SDK provided by the API. This can reduce the value of the API documentation and also lead to inconsistent integrations depending on whether a user discovers the API Docs or the SDK first.

The x-codeSamples (previously called x-code-samples) is a widely accepted spec extension that enables the addition off custom code samples in one or more languages to operationIds in your OpenAPI specification. When added documentation providers will render the usage snippet in the right hand panel of the documentation page.

An example below:

Screenshot of Inkeep's API docs showing featured SDK usage.

Anatomy of the extension

Field NameTypeDescriptionRequired
langstringThe language of the code snippet. Can be one form this list (opens in a new tab)Yes
labelstringCode sample label, for example Node or Python3, optional, lang is used by default.No
sourcestringThe code sample source code. In this case the SDK usage snippetYes

Documentation providers that support x-codeSamples include but not limited to:

  • Mintlify
  • Readme
  • Redocly
  • Stoplight

Example usage

Here is a basic example of how to use the x-codeSamples extension with a curl snippet.


openapi: '3.0.3'
info: ...
tags: [...]
paths:
/example:
get:
summary: Example summary
description: Example description
operationId: examplePath
responses: [...]
parameters: [...]
x-codeSamples:
- lang: 'cURL'
label: 'CLI'
source: |
curl --request POST \
--url 'https://data.apiexample.com/api/example/batch_query/json?format=json' \
--header 'content-type: application/octet-stream: ' \
--data '{}'

Now lets extend this to a more complex example of a Typescript SDK for a llm chat API.


openapi: '3.0.3'
info: ...
tags: [...]
paths:
/chat_sessions/chat_results:
post:
summary: Create Chat Session
operationId: create
tags: [chat_session]
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/CreateChatSession'
required: true
x-codeSamples:
- lang: 'typescript'
label: 'create_chat_session'
source: |
import { ChatSDK } from "@llm/chat-sdk";
async function run() {
const sdk = new ChatSDK({
apiKey: "<API_KEY>",
});
const res = await sdk.chatSession.create({
integrationId: "<interagtion_id>",
chatSession: {
messages: [
{
role: "user",
content: "How do I get started?",
},
],
},
stream: true,
});
/* Example of handling a streamed response */
if (res.chatResultStream == null) {
throw new Error("failed to create stream: received null value");
}
let chatSessionId: string | undefined | null = undefined;
for await (const event of res.chatResultStream) {
if (event.event == "message_chunk") {
console.log("Partial message: " + event.data.contentChunk);
chatSessionId = event.data.chatSessionId;
}
if (event.event == "records_cited") {
console.log("Citations: ", JSON.stringify(event.data.citations, null, 2));
}
}
}
run();

Multiple code samples can be added to a single operationId to support examples in any number of languages. This is possible by adding multiple keys under the x-codeSamples extension.


openapi: '3.0.3'
info: ...
tags: [...]
paths:
/chat:
get:
summary: Example summary
description: Example description
operationId: examplePath
responses: [...]
parameters: [...]
x-codeSamples:
- lang: 'typescript'
label: 'chat_ts'
source: |
.....
.....
- lang: 'python'
label: 'chat_python'
source: |
.....
.....

Generating Code Samples

To generate sdk code samples for your OpenAPI document simply run the following command. It will create an overlay with code samples for every operationId in your OpenAPI document.


speakeasy generate codeSamples -s {{your-spec.yaml}} --langs {{lang1}},{{lang2}} --out code-samples-overlay.yaml

To apply the overlay to your specification run


speakeasy overlay apply -o code-samples-overlay.yaml -s {{your-spec.yaml}} -o {{output-spec.yaml}}

The final output spec will include codeSamples inline.

Adding Code Sample Generation To Your Workflow

To include codeSamples overlay generation in your Speakeasy workflow add the following to your .speakeasy/workflow.yaml for any target thay you have configured.

.speakeasy/workflow.yaml

targets:
my-target:
target: typescript
source: my-source
codeSamples:
output: codeSamples.yaml

If you want the overlay to be automatically applied on the source create another workflow entry using speakeasy configure as follows.

Configure Sources 1

We'll now add the overlay created by Speakeasy to inject code snippets into your spec.

Configure Sources 2

Finally provide name and path for your output openapi spec. This will the final spec used by Mintlify.

Configure Sources 3