The Code Samples API
Note
This feature is for Speakeasy Enterprise customers. To inquire about access, please contact a Speakeasy representative, or book a demo.
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
IMPORTANT
To use the Code Samples API, the following prerequisites are required:
- A Speakeasy Enterprise Subscription,
- An Automated Code Sample URL, 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.
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
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:
import { SpeakeasyCodeSamplesCore } from "@speakeasyapi/code-samples/core";
import {
CodeSampleFilenameTitle,
CodeSamplesViewer,
SpeakeasyCodeSamplesProvider,
} from "@speakeasyapi/code-samples/react";
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}>
<CodeSamplesViewer
copyable
defaultLang={"typescript"}
title={CodeSampleFilenameTitle}
operation={"getPassageText"}
// client={speakeasyCodeSamples}
// 👆 optional, to pass the client directly
// instead of using the context provider
/>
</SpeakeasyCodeSamplesProvider>
);
}REST API Reference
Retrieve usage snippets
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.
Query Parameters
registry_url required, type: string
- Description: The registry URL from which to retrieve the snippets
- Example:
https://spec.speakeasy.com/my-org/my-workspace/my-source
operation_ids type: string[]
- Description: The operation IDs to retrieve snippets for
- Example:
getPets
method_paths type: { method: string, path: string }[]
- Description: The method paths to retrieve snippets for
- Example:
[{"method": "get", "path": "/pets"}]
languages type: string[]
- Description: The programming languages to retrieve snippets for
- Example:
["python", "javascript"]
Example Request
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"Example Response
{
"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();"
}
]
}{
"status_code": 404,
"message": "no snippets found for given operation IDs and languages -- err_not_found: not found"
}Generate usage snippets from example usage
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.
Request Body
oas required, type: object
- Description: The OpenAPI specification document that defines the API
- Example: A valid OpenAPI 3.x specification object
request required, type: object
- Description: The HTTP request example to use in the generated snippet
- Properties:
method: HTTP method (GET, POST, etc.)url: The request URLhttpVersion: HTTP versionheaders: Array of request headersqueryString: Array of query parameterscookies: Array of cookiesheadersSize: Size of headers in bytesbodySize: Size of body in bytes
language required, type: string
- Description: The target programming language for the generated SDK code
- Example:
"typescript","python","go","java"
speakeasy_spec_url type: string
- Description: Optional Speakeasy registry URL for additional context
- Example:
"https://spec.speakeasy.com/my-org/my-workspace/my-source:1.0.0"
Example Request
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"
}'Response
Success Response (200)
Returns a single SDK code snippet for the matched operation:
code: The generated SDK code in the specified languagename: The operation name (typically theoperationIdfrom the OpenAPI spec)install: Installation instructions for the SDK
Note
Installation instructions are not currently supported for /v1/code_sample/from_example calls. The install field will return “installation not yet supported”.
{
"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"
}{
"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"
}Last updated on