Last updated

OpenAPI extension: x-codeSamples

Code samples are snippets of code shown alongside API operations in reference documentation, giving users a quick way to start to interact with an API from their own code. The x-codeSamples addition to OpenAPI allows you to add or override any existing code samples for a particular language or endpoint.

Use the x-codeSamples option to make code samples part of the API description, or to replace the generated examples with code that is specific to your use case, such as using a custom library or SDK.

Language options

Control the list of language options by adjusting the theme.openapi.code-samples configuration setting.

Location

x-codeSamples can be added to Operation objects.

Options

Field NameTypeDescription
x-codeSamples[ Code Sample Object ]A list of code samples associated with an operation.

Code Sample Object

Field NameTypeDescription
langstringREQUIRED Code sample language, should be one of the github-linguist languages
sourcestringREQUIRED Code sample source code, or a $ref to the file containing the code sample.

Examples

The following partial OpenAPI snippet shows adding code samples to replace the generated samples for the getMuseumHours operation. One adds the source to the OpenAPI file, the other references a file containing the code sample.


...
paths:
  /museum-hours:
    get:
      summary: Get museum hours
      description: Get upcoming museum operating hours.
      operationId: getMuseumHours
      x-codeSamples:
        - lang: PHP
          source: |
            <?php
              $url = "https://example.com/museum";
              $response = file_get_contents($url);
              $data = json_decode($response);
        - lang: Python
          source:
            $ref: "code_samples/python.py"
      tags:
        - Operations

Resources