Speakeasy Logo
Skip to Content

What is the code samples extension?

Many API documentation providers 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, which reduces the value of the API documentation and can 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) extension is a widely accepted spec extension that enables the addition of custom code samples in one or more languages to operation IDs in your OpenAPI specification. When custom code samples are added using the code samples extension, documentation providers will render the usage snippet in the right-hand panel of the documentation page:

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

Anatomy of the extension

Field Name
lang
Type
string
Description
The language of the code snippet. Can be one from this list .
Required
Yes
label
Type
string
Description
Code sample label, for example,
or
. The
value is used by default.
Required
No
source
Type
string
Description
The code sample source code. In this case, the SDK usage snippet.
Required
Yes

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

  • Mintlify
  • Readme
  • Redocly
  • Stoplight

Example usage

Here is a basic example of using the x-codeSamples extension with a curl snippet.

Now let’s extend this to a more complex example: a TypeScript SDK for an LLM chat API.

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

Generating code samples

To generate SDK code samples for your OpenAPI document, run the following command:

This command creates an overlay with code samples for every operationId in your OpenAPI document.

To apply the overlay to your specification, run:

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 you have configured:

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

Configure Sources 1

Then add the overlay created by Speakeasy to inject code snippets into your spec:

Configure Sources 2

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

Configure Sources 3

Last updated on