Tutorials & Guides
How to Build a Local CLI Tool to Auto-Generate OpenAPI Schemas from Express Route Files with Claude 3.5 Sonnet
Stop writing OpenAPI YAML files by hand. Learn how to build a local Node.js CLI that feeds your raw Express.js router files to Claude 3.5 Sonnet and outputs production-ready Swagger specs.
Updated 11/18/2026
Writing OpenAPI (Swagger) specifications is one of those developer tasks that feels like a collective punishment. You write clean, expressive Express.js routers, implement validation middleware, map out your controllers, and then... you have to write a massive, 1,000-line YAML file explaining exactly what you just did.
If you don't update it manually with every pull request, your documentation drifts, your frontend team gets angry, and client integrations break.
We can do better. By building a local, lightweight CLI tool powered by /platforms/claude, you can automatically parse your raw Express route files and generate valid, production-ready OpenAPI 3.0 schemas in seconds. Let's build a Node-based CLI that runs locally, reads your routing files, and writes out a clean openapi.json file without you ever touching a YAML key again.
Why Use Claude 3.5 Sonnet for This?
Traditional AST (Abstract Syntax Tree) parsers struggle with Express routes because of the sheer variety in how developers write JavaScript. One file might use nested router structures, another might import controllers from external files, and payload validation might be handled by Joi, Zod, or custom middleware.
Claude 3.5 Sonnet excels at reasoning through messy, multi-file codebases and mapping dynamic JS patterns to static OpenAPI standards. It understands what makes these frameworks tick, effortlessly linking schema definitions to their actual route handlers. If it encounters a validation schema import, it can infer the expected shape of the request body with shocking accuracy.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
Step 1: Project Setup and Dependencies
First, let's set up a new Node.js workspace. Ensure you have Node 18+ installed, then initialise your project:
`bash
mkdir express-to-openapi
cd express-to-openapi
npm init -y
`
We will write our CLI tool using modern ESM. Open your package.json and add "type": "module":
`json
{
"name": "express-to-openapi",
"version": "1.0.0",
"type": "module",
"bin": {
"gen-spec": "./bin/index.js"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.28.0",
"commander": "^11.1.0",
"dotenv": "^16.4.5",
"glob": "^10.3.10"
}
}
`
Install the dependencies:
`bash
npm install
`
Create your directory structure:
`bash
mkdir bin
touch bin/index.js .env
`
Now, grab an API key from your Anthropic Console and add it to your .env file:
`env
ANTHROPIC_API_KEY=your_actual_api_key_here
`
Step 2: Crafting the System Prompt
The intelligence of our tool relies entirely on how we instruct Claude. We need a system prompt that forces Claude to output only raw, valid JSON without markdown formatting wraps (like `json ... `) so we can write the output directly to disk.
If you want to customise this prompt later for other routers (like Fastify or NestJS), you can use our /prompts to refine your system instructions.
Create a file named src/prompt.js:
`javascript
export const systemPrompt = `
You are an expert API documentation assistant. Your job is to parse the contents of Express.js route files and generate a single, unified OpenAPI 3.0.0 spec in JSON format.
Requirements:
1. Your response MUST be valid JSON and nothing else. Do not wrap the JSON in markdown code blocks, do not write markdown descriptions, and do not output any introductory or concluding conversational text.
2. Ensure you parse all HTTP methods (GET, POST, PUT, DELETE, PATCH, etc.).
3. Infer path parameters from routes (e.g., /users/:id becomes /users/{id}).
4. Try to infer the request body schemas by looking at variables, comments, or Joi/Zod validators referenced in the route controllers.
5. Map out reasonable HTTP responses (e.g., 200 OK, 400 Bad Request, 500 Internal Server Error).
6. Do not make up routes that are not in the source code provided.
`;
`
Step 3: Writing the CLI Core
Now, we’ll build the script that scans the directory, reads the targets, bundles them together, and ships the payload over to the Anthropic API.
Open bin/index.js and add the following code:
`javascript
#!/usr/bin/env node
import { Command } from 'commander'; import { glob } from 'glob'; import fs from 'fs'; import path from 'path'; import Anthropic from '@anthropic-ai/sdk'; import dotenv from 'dotenv'; import { systemPrompt } from '../src/prompt.js';
dotenv.config();
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, });
const program = new Command();
program .name('gen-spec') .description('Generate an OpenAPI schema from Express route files using Claude') .version('1.0.0') .requiredOption('-i, --input <pattern>', 'Glob pattern of files to process (e.g., "routes/*/.js")') .requiredOption('-o, --output <path>', 'Destination output file (e.g., "swagger.json")') .option('-t, --title <title>', 'API Title', 'Express API') .action(async (options) => { try { const files = await glob(options.input); if (files.length === 0) { console.error('No matching route files found with the provided pattern.'); process.exit(1); }
console.log(Found ${files.length} route file(s). Reading contents...);
let bundledCode = '';
for (const file of files) {
const content = fs.readFileSync(file, 'utf-8');
bundledCode += \n\n--- FILE: ${path.basename(file)} ---\n${content};
}
console.log('Analysing code and generating spec with Claude 3.5 Sonnet...');
const message = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 4000,
temperature: 0.1, // Low temperature for consistent JSON structure
system: systemPrompt,
messages: [
{
role: 'user',
content: Analyze the following Express route definitions and build an OpenAPI schema with the title "${options.title}".\n\n${bundledCode}
}
]
});
let responseText = message.content[0].text.trim();
// Clean up markdown block wraps if Claude accidentally adds them
if (responseText.startsWith('`json')) {
responseText = responseText.replace(/^`json/, '').replace(/`$/, '').trim();
} else if (responseText.startsWith('`')) {
responseText = responseText.replace(/^`/, '').replace(/`$/, '').trim();
}
// Validate that Claude returned true JSON
try {
const parsedJson = JSON.parse(responseText);
fs.writeFileSync(options.output, JSON.stringify(parsedJson, null, 2), 'utf-8');
console.log(\x1b[32m✔ Successfully generated OpenAPI schema at: ${options.output}\x1b[0m);
} catch (err) {
console.error('\x1b[31mError: Claude output was not valid JSON.\x1b[0m');
console.log('Writing raw output to debug.txt to help you troubleshoot.');
fs.writeFileSync('debug.txt', responseText, 'utf-8');
}
} catch (error) { console.error('An unexpected error occurred:', error.message); process.exit(1); } });
program.parse(process.argv);
`
Make your CLI binary executable locally:
`bash
chmod +x bin/index.js
npm link
`
Step 4: Testing Your New CLI Tool
Let’s test this setup. Create a dummy Express route file in a new directory named routes/users.js:
`javascript
import express from 'express';
const router = express.Router();
/** * @route GET /api/users * @desc Fetch all users with optional pagination */ router.get('/users', (req, res) => { const { limit, page } = req.query; res.json({ success: true, data: [] }); });
/** * @route POST /api/users * @desc Create a new user */ router.post('/users', (req, res) => { const { username, email, password } = req.body; if (!username || !email) { return res.status(400).json({ error: 'Missing fields' }); } res.status(201).json({ id: 42, username, email }); });
export default router;
`
Now execute your CLI to scan this route file and output your spec:
`bash
gen-spec -i "routes/*/.js" -o "openapi.json" --title "Users Microservice"
`
Within seconds, you should see the green success message, and a freshly generated openapi.json will appear in your root directory. Open it, and you will find your endpoints, parameters, request body schemas, and HTTP status codes fully mapped out.
Advanced: Handling Mid-Sized API Codebases
If you have a larger codebase, you might run into a few hurdles:
- Token Limits: For very large APIs, sending dozens of route files at once will exceed Claude's token window. It is highly recommended to split your API documentation generation by logical domain (e.g., generate a separate file for
/billing,/users, and/auth) and then merge the outputs. - External Types: If your schemas are defined using TypeScript interfaces or Joi validation files, pass those schema definitions explicitly as context along with your route files inside your inputs so Claude has access to the full type tree.
If your CLI encounters API connection timeouts, errors, or limits, you can look for common strategies in our troubleshooting guides over at /platforms/claude/articles to handle high-volume processing gracefully.
Now, with just a single tick of the build clock in your CI pipeline, you can auto-generate documentation and keep your API specs and routing files in complete harmony forever.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.