/speakeasy:extract-openapi-from-codefrom speakeasy
Extracts or generates an OpenAPI spec from existing API code across eight frameworks: FastAPI, Flask, Django REST Framework, Spring Boot, NestJS, Hono, Rails, and Laravel.
Ships in speakeasy. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Extract an OpenAPI specification from an existing API codebase. Covers eight major frameworks across Python, Java, JavaScript/TypeScript, Ruby, and PHP.
| Framework | Language | Guide |
|---|---|---|
| FastAPI | Python | content/frameworks/fastapi.md |
| Flask | Python | content/frameworks/flask.md |
| Django REST Framework | Python | content/frameworks/django.md |
| Spring Boot | Java | content/frameworks/spring-boot.md |
| NestJS | TypeScript | content/frameworks/nestjs.md |
| Hono | TypeScript | content/frameworks/hono.md |
| Rails | Ruby | content/frameworks/rails.md |
| Laravel | PHP | content/frameworks/laravel.md |
Each guide provides detailed setup, schema definition, Speakeasy extensions, authentication, and troubleshooting for that framework.
| Input | Required | Description |
|---|---|---|
| Framework | Yes | The API framework in use (see Decision Framework) |
| Project path | Yes | Root directory of the API project |
| Output path | No | Where to write the spec (default: openapi.json or openapi.yaml) |
| Target language | No | SDK target language, if generating an SDK after extraction |
| Output | Description |
|---|---|
| OpenAPI spec | A JSON or YAML file describing the API |
| Validation report | Lint results from speakeasy lint |
speakeasy CLI installed for post-extraction validation and SDK generationUse this tree to determine the extraction method:
| Framework | Language | Method | Requires Running Server? |
|---|---|---|---|
| FastAPI | Python | Built-in export | No |
| Flask (flask-smorest) | Python | CLI command | No |
| Django REST Framework | Python | drf-spectacular CLI | No |
| Spring Boot (springdoc) | Java | HTTP endpoint | Yes |
| NestJS | TypeScript | HTTP endpoint or script | Yes |
| Hono (zod-openapi) | TypeScript | Programmatic export | No |
| Rails (rswag) | Ruby | Rake task | No |
| Laravel (l5-swagger) | PHP | Artisan command | No |
Choose the command matching your framework below. After extraction, always validate with speakeasy lint.
FastAPI generates an OpenAPI schema at runtime. Export it without starting the server:
python -c "import json; from myapp import app; print(json.dumps(app.openapi()))" > openapi.json
Replace myapp with the module containing your FastAPI app instance. If the app uses a factory pattern:
python -c "import json; from myapp import create_app; app = create_app(); print(json.dumps(app.openapi()))" > openapi.json
You can also start the server and fetch from http://localhost:8000/openapi.json.
Requires flask-smorest or apispec:
flask openapi write openapi.json
If using apispec directly, export programmatically:
import json
from myapp import create_app, spec
app = create_app()
with app.app_context():
print(json.dumps(spec.to_dict()))
Requires drf-spectacular:
python manage.py spectacular --file openapi.yaml
For JSON output:
python manage.py spectacular --format openapi-json --file openapi.json
Requires springdoc-openapi. Start the application, then fetch the spec:
# Start the app (background)
./mvnw spring-boot:run &
# Wait for startup
sleep 15
# Fetch the spec
curl http://localhost:8080/v3/api-docs -o openapi.json
# For YAML format
curl http://localhost:8080/v3/api-docs.yaml -o openapi.yaml
# Stop the app
kill %1
If the server runs on a different port or context path, adjust the URL accordingly.
Requires @nestjs/swagger. Start the application, then fetch:
# Start the app (background)
npm run start &
sleep 10
# Fetch the spec (default path with SwaggerModule)
curl http://localhost:3000/api-json -o openapi.json
# Stop the app
kill %1
Alternatively, create a script to export without running the server:
// scripts/export-openapi.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from '../src/app.module';
import * as fs from 'fs';
async function bootstrap() {
const app = await NestFactory.create(AppModule, { logger: false });
const config = new DocumentBuilder().setTitle('API').build();
const doc = SwaggerModule.createDocument(app, config);
fs.writeFileSync('openapi.json', JSON.stringify(doc, null, 2));
await app.close();
}
bootstrap();
Requires @hono/zod-openapi. Export the schema programmatically:
// scripts/export-openapi.ts
import { app } from '../src/app';
import * as fs from 'fs';
const doc = app.doc('/doc', {
openapi: '3.1.0',
info: { title: 'API', version: '1.0.0' },
});
fs.writeFileSync('openapi.json', JSON.stringify(doc, null, 2));
Run with:
npx tsx scripts/export-openapi.ts
Requires rswag:
rails rswag:specs:swaggerize
The spec is written to swagger/v1/swagger.yaml by default (configurable in config/initializers/rswag_api.rb).
Requires l5-swagger:
php artisan l5-swagger:generate
The spec is written to storage/api-docs/api-docs.json by default.
After extracting the spec, always run these steps:
speakeasy lint openapi --non-interactive -s openapi.json
If validation reveals issues, use an overlay rather than modifying the extracted spec directly:
speakeasy overlay apply -s openapi.json -o fixes.yaml
To fix validation errors, create an OpenAPI overlay file and apply it with speakeasy overlay apply -s <spec> -o <overlay>.
speakeasy quickstart --skip-interactive --output console \
-s openapi.json \
-t <target> \
-n <name> \
-p <package>
Run speakeasy quickstart -s <spec> -t <language> to initialize a new SDK project.
Full workflow for a FastAPI project:
# 1. Extract the OpenAPI spec
cd /path/to/my-fastapi-project
python -c "import json; from main import app; print(json.dumps(app.openapi()))" > openapi.json
# 2. Validate
speakeasy lint openapi --non-interactive -s openapi.json
# 3. Generate a TypeScript SDK
speakeasy quickstart --skip-interactive --output console \
-s openapi.json \
-t typescript \
-n "MyApiSDK" \
-p "my-api-sdk"
After extracting a spec, add Speakeasy-specific extensions for better SDK output. These can be added in framework config or via overlay.
openapi_extra@app.get(
"/items",
openapi_extra={
"x-speakeasy-retries": {
"strategy": "backoff",
"backoff": {"initialInterval": 500, "maxInterval": 60000, "exponent": 1.5},
"statusCodes": ["5XX", "429"]
},
"x-speakeasy-group": "items",
"x-speakeasy-name-override": "list"
}
)
def list_items(): ...
SPECTACULAR_SETTINGS# settings.py
SPECTACULAR_SETTINGS = {
# ... other settings
'EXTENSIONS_TO_SCHEMA_FUNCTION': lambda generator, request, public: {
'x-speakeasy-retries': {
'strategy': 'backoff',
'backoff': {'initialInterval': 500, 'maxInterval': 60000, 'exponent': 1.5},
'statusCodes': ['5XX']
}
}
}
OperationCustomizer@Bean
public OperationCustomizer operationCustomizer() {
return (operation, handlerMethod) -> {
operation.addExtension("x-speakeasy-group",
handlerMethod.getBeanType().getSimpleName().replace("Controller", "").toLowerCase());
return operation;
};
}
@Get()
@ApiOperation({
summary: 'List items',
operationId: 'listItems'
})
@ApiExtension('x-speakeasy-group', 'items')
@ApiExtension('x-speakeasy-name-override', 'list')
listItems() { ... }
If you cannot modify framework code, use an overlay:
overlay: 1.0.0
info:
title: Speakeasy Extensions
version: 1.0.0
actions:
- target: $.paths['/items'].get
update:
x-speakeasy-group: items
x-speakeasy-name-override: list
| Issue | Symptom | Fix |
|---|---|---|
| Missing operationIds | Lint warning; SDK methods get generic names | Add operationIds via overlay or use speakeasy suggest operation-ids -s openapi.json |
| Missing descriptions | Lint hints; SDK has no documentation | Add descriptions to endpoints and schemas in source code or via overlay |
| Overly permissive schemas | Schemas use additionalProperties: true or lack type constraints | Tighten schemas in source code; use stricter validation decorators |
| No response schemas | Lint errors; SDK return types are any/object | Add explicit response models to your framework endpoints |
| Duplicate operationIds | Lint errors; generation fails | Ensure each endpoint has a unique operationId |
| Missing authentication | No security schemes in spec | Add security metadata to your framework config or via overlay |
| Error | Cause | Solution |
|---|---|---|
ModuleNotFoundError (Python) | App dependencies not installed | Run pip install -r requirements.txt or pip install -e . |
| Connection refused (Spring Boot, NestJS) | Server not fully started | Increase sleep time or poll for readiness |
| Empty or minimal spec | Routes not registered at import time | Ensure all route modules are imported; check lazy loading |
| YAML parse error | Extracted file has invalid syntax | Re-extract; check for print statements polluting stdout |
Cannot find module (Node.js) | Dependencies not installed | Run npm install or yarn install |
No /v3/api-docs endpoint (Spring Boot) | springdoc not configured | Add springdoc-openapi-starter-webmvc-ui to dependencies |
No /api-json endpoint (NestJS) | Swagger module not set up | Configure SwaggerModule.setup(app, ...) in main.ts |
manage-openapi-overlays - Add x-speakeasy-* extensions via overlaystart-new-sdk-project - Generate SDK after extractioncontent/frameworks/django.md (opens in a new tab)content/frameworks/fastapi.md (opens in a new tab)content/frameworks/flask.md (opens in a new tab)content/frameworks/hono.md (opens in a new tab)content/frameworks/laravel.md (opens in a new tab)content/frameworks/nestjs.md (opens in a new tab)content/frameworks/rails.md (opens in a new tab)content/frameworks/spring-boot.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Fastapi, Flask, Django REST Framework, Spring Boot, NestJS, Hono, Rails, Laravel
openapi-extraction, api-spec-generation, code-first, speakeasy
14 skills in this plugin
/configure-sdk-optionsUse when CONFIGURING an existing SDK - NOT for initial generation. Covers gen.yaml configuration for all languages: TypeScript, Python, Go, Java, C#, PHP, Ruby. Also covers runtime overrides (retries, timeouts, server selection) in application code. Triggers on "configure SDK", "gen.yaml", "SDK options", "SDK config", "SDK configuration", "runtime override", "SDK client config", "override timeout", "per-call config". For NEW SDK generation, use start-new-sdk-project instead./customize-sdk-hooksUse when implementing SDK code hooks for custom logic (not spec configuration or runtime overrides).
Covers SDK lifecycle hooks: BeforeRequest, AfterSuccess, AfterError for custom headers,
telemetry, HMAC signing, and request/response transformation.
Triggers on "SDK hooks", "add hooks", "BeforeRequestHook", "custom logic in SDK",
"telemetry hook", "SDK middleware", "intercept requests", "HMAC signing hook",
"custom code in hooks directory".
/diagnose-generation-failureUse when SDK generation failed or seeing errors. Triggers on "generation failed", "speakeasy run failed", "SDK build error", "workflow failed", "Step Failed", "why did generation fail"/generate-mcp-serverUse when generating an MCP server from an OpenAPI spec with Speakeasy. Triggers on "generate MCP server", "MCP server", "Model Context Protocol", "AI assistant tools", "Claude tools", "speakeasy MCP", "mcp-typescript"/generate-terraform-providerUse when generating a Terraform provider from an OpenAPI spec with Speakeasy. Covers entity annotations, CRUD mapping, type inference, workflow configuration, and publishing. Triggers on "terraform provider", "generate terraform", "create terraform provider", "CRUD mapping", "x-speakeasy-entity", "terraform resource", "terraform registry"./improve-sdk-namingUse when you want AI-powered suggestions for SDK naming improvements via the `speakeasy suggest` command (not manual overlay creation). Triggers on "suggest improvements", "speakeasy suggest", "AI suggestions", "suggest operation-ids", "suggest error-types", "auto-improve naming", "get AI recommendations".Claude Code refuses to install this plugin
.claude-plugin/plugin.json: skills: Invalid string: must start with "./"
Checked against Claude Code 2.1.332's install rules. The listing below is what the repository ships; Claude Code cannot install it as published.
Other plugins' skills for the same job