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.
Control the list of language options by adjusting the openapi.code-samples configuration setting.
Location
x-codeSamples
can be added to Operation objects.
Options
Field Name | Type | Description |
---|---|---|
x-codeSamples | [ Code Sample Object ] | A list of code samples associated with an operation. |
Code Sample Object
Field Name | Type | Description |
---|---|---|
lang | string | REQUIRED Code sample language, should be one of the github-linguist languages |
source | string | REQUIRED 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
- Control the list of language options by adjusting the openapi.code-samples configuration setting.
- Control which extensions are included in your API reference documentation with the showExtensions configuration setting.
- See all openapi configuration settings.
- See a full list of supported OpenAPI extensions.