# The Code Samples API

<Callout title="Note" type="info">

This feature is for **Speakeasy Enterprise** customers. To inquire about
access, please contact a Speakeasy representative, or [book a demo](/book-demo).

</Callout>

## Overview

The Speakeasy Code Samples API is a streamlined solution for accessing rich,
up-to-date SDK usage examples for Speakeasy managed SDKs. These examples can be
easily integrated into an organization's documentation sites, tools, or
developer portal, and they'll stay up to date automatically.

This API is ideal for organizations who:

- Use Speakeasy to generate SDKs from OpenAPI specifications,
- Need reliable, up-to-date SDK usage examples for their APIs, and
- Want custom tooling for SDK code samples in their documentation.

## Usage

### Prerequisites

<Callout title="IMPORTANT" type="warning">

To use the Code Samples API, the following prerequisites are required:

- A Speakeasy Enterprise Subscription,
- An [Automated Code Sample URL](/docs/sdk-docs/code-samples/automated-code-sample-urls), configured for the desired
  Speakeasy SDK, and
- A Speakeasy API Key for the workspace associated with the desired SDK if the OpenAPI Document is not publicly accessible. [Learn more about
  making OpenAPI Document public on Speakeasy.](/docs/sdk-docs/integrations/_get-public-url-snippet)

</Callout>

### TypeScript SDK

The Code Samples SDK can be used in TypeScript projects to fetch snippets. The
library also ships with some convenient features such as **React Query hooks**, and
a **React Component**.

For instructions on how to install and use the TypeScript SDK, refer to the
[GitHub repo's README file](https://github.com/speakeasy-api/speakeasy-code-samples-ts/tree/main?tab=readme-ov-file#sdk-example-usage).

#### The React Component

This library includes a React component that fetches and highlights code
snippets using `codehike`. Along with displaying the snippet, it shows a
loading state during fetching and provides a fallback view if an error occurs.

The component can be used as follows:

```tsx filename="App.tsx"

const speakeasyCodeSamples = new SpeakeasyCodeSamplesCore({
  // optional if the registryUrl is publicly accessible
  apiKey: "<API_KEY_HERE>",
  registryUrl: "https://spec.speakeasy.com/org/ws/my-source",
});

function App() {
  return (
    <SpeakeasyCodeSamplesProvider client={speakeasyCodeSamples}>

    </SpeakeasyCodeSamplesProvider>
  );
}
```

## REST API Reference

<h3 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h4-mobile md:_text-h4">
  Retrieve usage snippets
</h3>

`GET /v1/code_sample`

Retrieves usage snippets from an OpenAPI document stored in the registry. The endpoint supports filtering by programming language and operation ID.

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _mb-4 _text-h5-mobile md:_text-h5">
  Query Parameters
</h4>

**`registry_url`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">required, type: string</span>

- **Description**: The registry URL from which to retrieve the snippets
- **Example**: `https://spec.speakeasy.com/my-org/my-workspace/my-source`

**`operation_ids`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">type: string[]</span>

- **Description**: The operation IDs to retrieve snippets for
- **Example**: `getPets`

**`method_paths`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">type: {`{ method: string, path: string }[]`}</span>

- **Description**: The method paths to retrieve snippets for
- **Example**: `[{"method": "get", "path": "/pets"}]`

**`languages`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">type: string[]</span>

- **Description**: The programming languages to retrieve snippets for
- **Example**: `["python", "javascript"]`

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h5-mobile md:_text-h5">
  Example Request
</h4>

```shell filename="example-request.sh"  
curl -G "https://app.speakeasy.com/v1/code_sample" \
  -H "X-Api-Key: <SPEAKEASY_API_KEY_HERE>" \
  --data-urlencode "registry_url=https://spec.speakeasy.com/my-org/my-workspace/my-source" \
  -d "languages=go" \
  -d "languages=typescript" \
  -d "operation_ids=getPets"
```

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h5-mobile md:_text-h5">
  Example Response
</h4>

```json filename="200 - Success"
{
  "snippets": [
    {
      "operationId": "getPetById",
      "path": "/pet/{id}",
      "method": "get",
      "language": "typescript",
      "code": "import { Petstore } from \"petstore-sdk\";\n\nconst petstore = new Petstore({\n  apiKey: \"<API_KEY_HERE>\",\n});\n\nasync function run() {\n  const result = await petstore.pet.getById({\n    id: 137396,\n  });\n\n  // Handle the result\n  console.log(result);\n}\n\nrun();"
    }
  ]
}
```

```json filename="4XX - Error"
{
  "status_code": 404,
  "message": "no snippets found for given operation IDs and languages -- err_not_found: not found"
}
```

<h3 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h4-mobile md:_text-h4">
  Generate usage snippets from example usage
</h3>

`POST /v1/code_sample/from_example`

Generates a single code snippet from the provided examples in an OpenAPI document. This endpoint optionally takes in a `speakeasy_spec_url` to specify which generation configuration to use. This is useful in circumstances where there are multiple configurations for the language target.

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _mb-4 _text-h5-mobile md:_text-h5">
  Request Body
</h4>

**`oas`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">required, type: object</span>

- **Description**: The OpenAPI specification document that defines the API
- **Example**: A valid OpenAPI 3.x specification object

**`request`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">required, type: object</span>

- **Description**: The HTTP request example to use in the generated snippet
- **Properties**:
  - `method`: HTTP method (GET, POST, etc.)
  - `url`: The request URL
  - `httpVersion`: HTTP version
  - `headers`: Array of request headers
  - `queryString`: Array of query parameters
  - `cookies`: Array of cookies
  - `headersSize`: Size of headers in bytes
  - `bodySize`: Size of body in bytes

**`language`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">required, type: string</span>

- **Description**: The target programming language for the generated SDK code
- **Example**: `"typescript"`, `"python"`, `"go"`, `"java"`

**`speakeasy_spec_url`** <span className="text-xs font-secondary-mono text-brand-warning-500 ml-2">type: string</span>

- **Description**: Optional Speakeasy registry URL for additional context
- **Example**: `"https://spec.speakeasy.com/my-org/my-workspace/my-source:1.0.0"`

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h5-mobile md:_text-h5">
  Example Request
</h4>

```shell filename="example-request.sh"
curl -s -X POST https://app.speakeasy.com/v1/code_sample/from_example \
  -H "Content-Type: application/json" \
  -H "x-api-key: <SPEAKEASY_API_KEY_HERE>" \
  -d '{
    "oas": {
      "openapi": "3.0.2",
      "info": {
        "title": "Swagger Petstore - OpenAPI 3.0",
        "description": "This is a sample Pet Store Server based on the OpenAPI 3.0 specification.",
        "version": "1.0.0"
      },
      "paths": {
        "/pet/{petId}": {
          "get": {
            "tags": ["pet"],
            "summary": "Find pet by ID",
            "description": "Returns a single pet",
            "operationId": "getPetById",
            "parameters": [
              {
                "name": "petId",
                "in": "path",
                "description": "ID of pet to return",
                "required": true,
                "schema": {
                  "type": "integer",
                  "format": "int64"
                }
              }
            ],
            "responses": {
              "200": {
                "description": "successful operation",
                "content": {
                  "application/json": {
                    "schema": {
                      "$ref": "#/components/schemas/Pet"
                    }
                  }
                }
              },
              "400": {
                "description": "Invalid ID supplied"
              },
              "404": {
                "description": "Pet not found"
              }
            },
            "security": [
              {
                "api_key": []
              }
            ]
          }
        }
      },
      "components": {
        "schemas": {
          "Pet": {
            "required": ["name", "photoUrls"],
            "type": "object",
            "properties": {
              "id": {
                "type": "integer",
                "format": "int64",
                "example": 10
              },
              "name": {
                "type": "string",
                "example": "doggie"
              },
              "category": {
                "$ref": "#/components/schemas/Category"
              },
              "photoUrls": {
                "type": "array",
                "items": {
                  "type": "string"
                }
              },
              "tags": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/Tag"
                }
              },
              "status": {
                "type": "string",
                "description": "pet status in the store",
                "enum": ["available", "pending", "sold"]
              }
            }
          },
          "Category": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer",
                "format": "int64",
                "example": 1
              },
              "name": {
                "type": "string",
                "example": "Dogs"
              }
            }
          },
          "Tag": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer",
                "format": "int64"
              },
              "name": {
                "type": "string"
              }
            }
          }
        },
        "securitySchemes": {
          "api_key": {
            "type": "apiKey",
            "name": "api_key",
            "in": "header"
          }
        }
      }
    },
      "request": {
      "cookies": [],
      "headers": [
        {
          "name": "api_key",
          "value": "special-key"
        }
      ],
      "headersSize": 35,
      "queryString": [],
      "bodySize": 0,
      "method": "GET",
      "url": "https://petstore3.swagger.io/api/v3/pet/10",
      "httpVersion": "HTTP/1.1"
     },
     "language": "typescript",
     "speakeasy_spec_url": "https://spec.speakeasy.com/my-org/my-workspace/my-source:1.0.0"
   }'
```

<h4 className="_tracking-tight _text-slate-900 dark:_text-white _mt-10 _text-h5-mobile md:_text-h5">
  Response
</h4>

**Success Response (200)**

Returns a single SDK code snippet for the matched operation:

- **`code`**: The generated SDK code in the specified language
- **`name`**: The operation name (typically the `operationId` from the OpenAPI spec)
- **`install`**: Installation instructions for the SDK

<Callout title="Note" type="info">

Installation instructions are not currently supported for `/v1/code_sample/from_example` calls. The `install` field will return "installation not yet supported".

</Callout>

```json filename="200 - Success"
{
  "code": "import { Petstore } from \"petstore\";\n\nconst petstore = new Petstore({\n  serverURL: \"https://api.example.com\",\n  apiKey: process.env[\"PETSTORE_API_KEY\"] ?? \"\",\n});\n\nasync function run() {\n  const result = await petstore.pet.getPetById({\n    petId: 311674,\n  });\n\n  // Handle the result\n  console.log(result);\n}\n\nrun();",
  "name": "getPetById",
  "install": "installation not yet supported"
}
```

```json filename="500 - Error"
{
  "status_code": 500,
  "message": "failed to get generation config for speakeasy spec url -- no successful generation config found for language python and spec https://spec.speakeasy.com/my-org/my-workspace/my-source:1.0.0"
}
```
