API Documentation Builder
by @michaelatamuk
Generate comprehensive API documentation from code with examples, types, and OpenAPI specs
clawhub install api-doc-builderπ About This Skill
name: api-doc-builder description: Generate comprehensive API documentation from code with examples, types, and OpenAPI specs version: 1.0.3 metadata: openclaw: emoji: "π" homepage: https://swagger.io/specification/ requires: env: [] bins: - node os: ["macos", "linux", "windows"]
API Documentation Generator
> No credentials required. This skill reads only local source files you point it at. The authentication examples throughout this document (Bearer tokens, API keys, OAuth) are patterns to *document in your API docs* β not credentials the skill itself needs or requests.
Automatically generates comprehensive, developer-friendly API documentation from your source code. Analyzes endpoints, parameters, return types, and generates documentation in multiple formats including Markdown, OpenAPI/Swagger specs, and interactive API explorers.
What This Skill Does
This skill analyzes your API code and generates complete documentation including:
Supports multiple frameworks and languages:
Why Use This Skill
Saves Massive Time
Writing API documentation manually is tedious:
Easier to Keep Up-to-Date
Regenerating is fast, so docs can follow code more closely:
Improves API Adoption
Well-documented APIs are used more:
Enables Automation
Generated OpenAPI specs enable:
When to Use This Skill
Use this skill whenever you need API documentation:
When NOT to Use This Skill
How It Works
Step-by-Step Process
1. Analyzes route definitions: Extracts HTTP methods, paths, middleware 2. Parses function signatures: Identifies parameters, request bodies, responses 3. Reads TypeScript types: Uses type information for schemas 4. Extracts JSDoc comments: Incorporates developer-written descriptions 5. Detects validation: Identifies Zod, Joi, class-validator rules 6. Generates examples: Creates realistic request/response samples 7. Builds OpenAPI spec: Produces valid OpenAPI 3.0 YAML/JSON 8. Creates markdown docs: Human-readable documentation 9. Adds interactive elements: curl examples, code snippets
Documentation Structure
For each endpoint:
Usage Examples
Example 1: Express.js REST API
Your code:
// src/api/users.ts
import { Router } from 'express';
import { z } from 'zod';const router = Router();
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(2),
age: z.number().int().min(18).optional()
});
/**
* Create a new user
* @auth Required - Bearer token
* @ratelimit 10 requests per minute
*/
router.post('/users', async (req, res) => {
const data = CreateUserSchema.parse(req.body);
const user = await db.users.create(data);
res.status(201).json(user);
});
/**
* Get user by ID
* @param id - User ID (UUID format)
*/
router.get('/users/:id', async (req, res) => {
const user = await db.users.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
});
export default router;
Ask Claude:
"Generate API documentation for the users API in src/api/users.ts"
Generated Markdown Documentation:
# Users APIEndpoints
Create User
Creates a new user account.
Endpoint: POST /users
Authentication: Required (Bearer token)
Rate Limit: 10 requests per minute
Request Body:
json
{
"email": "user@example.com",
"name": "John Doe",
"age": 25
}
Request Schema:
| Field | Type | Required | Validation | Description |
|-------|------|----------|------------|-------------|
| email | string | Yes | Valid email format | User email address |
| name | string | Yes | Min 2 characters | User full name |
| age | integer | No | Min 18 | User age (must be 18+) |Success Response (201 Created):
json
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"name": "John Doe",
"age": 25,
"createdAt": "2024-01-15T10:30:00Z"
}
Error Responses:400 Bad Request - Invalid input data
json
{
"error": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
401 Unauthorized - Missing or invalid authentication
json
{
"error": "Authentication required"
}
429 Too Many Requests - Rate limit exceeded
json
{
"error": "Rate limit exceeded",
"retryAfter": 45
}
Example Request:
bash
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"email": "john@example.com",
"name": "John Doe",
"age": 25
}'
Example Request (JavaScript):
javascript
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({
email: 'john@example.com',
name: 'John Doe',
age: 25
})
});const user = await response.json(); console.log(user);
Get User by ID
Retrieves a user by their unique identifier.
Endpoint: GET /users/:id
Authentication: Not required
Path Parameters:
| Parameter | Type | Format | Description |
|-----------|------|--------|-------------|
| id | string | UUID | User unique identifier |
Success Response (200 OK):
json
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"name": "John Doe",
"age": 25,
"createdAt": "2024-01-15T10:30:00Z"
}
Error Responses:404 Not Found - User does not exist
json
{
"error": "User not found"
}
Example Request:
bash
curl https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000
Example Request (JavaScript):
javascript
const userId = '550e8400-e29b-41d4-a716-446655440000';
const response = await fetch(https://api.example.com/users/${userId});
const user = await response.json();
Generated OpenAPI Specification:
openapi: 3.0.0
info:
title: Users API
version: 1.0.0
description: User management endpointsservers:
- url: https://api.example.com
description: Production server
paths:
/users:
post:
summary: Create User
description: Creates a new user account
operationId: createUser
tags:
- Users
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- email
- name
properties:
email:
type: string
format: email
example: user@example.com
name:
type: string
minLength: 2
example: John Doe
age:
type: integer
minimum: 18
example: 25
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid input data
content:
application/json:
schema:
$ref: '#/components/schemas/ValidationError'
'401':
description: Authentication required
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'429':
description: Rate limit exceeded
content:
application/json:
schema:
$ref: '#/components/schemas/RateLimitError'
/users/{id}:
get:
summary: Get User by ID
description: Retrieves a user by their unique identifier
operationId: getUserById
tags:
- Users
parameters:
- name: id
in: path
required: true
description: User unique identifier
schema:
type: string
format: uuid
responses:
'200':
description: User found
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
User:
type: object
properties:
id:
type: string
format: uuid
example: 550e8400-e29b-41d4-a716-446655440000
email:
type: string
format: email
example: user@example.com
name:
type: string
example: John Doe
age:
type: integer
example: 25
createdAt:
type: string
format: date-time
example: 2024-01-15T10:30:00Z
Error:
type: object
properties:
error:
type: string
example: An error occurred
ValidationError:
type: object
properties:
error:
type: string
example: Validation failed
details:
type: array
items:
type: object
properties:
field:
type: string
message:
type: string
RateLimitError:
type: object
properties:
error:
type: string
example: Rate limit exceeded
retryAfter:
type: integer
example: 45
Example 2: Next.js API Routes
Your code:
// app/api/posts/route.ts
import { NextRequest, NextResponse } from 'next/server';export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const page = parseInt(searchParams.get('page') || '1');
const limit = parseInt(searchParams.get('limit') || '10');
const posts = await db.posts.findMany({
skip: (page - 1) * limit,
take: limit,
orderBy: { createdAt: 'desc' }
});
return NextResponse.json({
data: posts,
pagination: {
page,
limit,
total: await db.posts.count()
}
});
}
export async function POST(request: NextRequest) {
const body = await request.json();
// Validation
if (!body.title || !body.content) {
return NextResponse.json(
{ error: 'Title and content are required' },
{ status: 400 }
);
}
const post = await db.posts.create({
data: {
title: body.title,
content: body.content,
authorId: body.authorId
}
});
return NextResponse.json(post, { status: 201 });
}
Ask Claude:
"Generate API docs for the posts API routes"
Generated Documentation includes:
Example 3: FastAPI (Python)
Your code:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStrapp = FastAPI()
class CreateUser(BaseModel):
email: EmailStr
name: str
age: int | None = None
@app.post("/users", response_model=User, status_code=201)
async def create_user(user_data: CreateUser):
"""
Create a new user.
- email: Valid email address
- name: User's full name
- age: Optional age (must be 18+)
"""
if user_data.age and user_data.age < 18:
raise HTTPException(status_code=400, detail="Must be 18 or older")
user = await db.create_user(user_data)
return user
Ask Claude:
"Generate OpenAPI docs for this FastAPI application"
Generated: Complete OpenAPI spec with Pydantic model schemas automatically converted.
Configuration
Specify Output Format
"Generate Markdown API documentation"
"Create OpenAPI 3.0 specification in YAML"
"Generate both Markdown docs and OpenAPI spec"
"Create Postman collection from this API"
Customize Documentation Style
"Generate API docs in README format"
"Create comprehensive API reference with all examples"
"Generate minimal API docs (endpoints and parameters only)"
Include/Exclude Sections
"Generate API docs without rate limiting info"
"Include authentication details in the documentation"
"Add TypeScript client examples to the docs"
Best Practices
For Best Results
1. Add JSDoc comments: Claude uses them for descriptions 2. Use TypeScript types: Better schema generation 3. Define validation schemas: Zod, Joi, class-validator 4. Document auth requirements: Comment with @auth tags 5. Include examples in code: Sample data helps generate realistic examples 6. Group related endpoints: Organize by resource (users, posts, etc.)
Documentation Quality Checklist
Ensure generated docs include:
Keeping Docs Updated
# Regenerate after API changes
"Regenerate API documentation after recent changes"Compare versions
"Show API changes between v1 and v2"Generate changelog
"Create API changelog from code changes"
Integration with Tools
Swagger UI
Host interactive API docs:
npm install swagger-ui-expressserver.ts
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './openapi.json';app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Postman
Import OpenAPI spec: 1. Open Postman 2. Import β Link β Paste OpenAPI URL 3. Generate collection with all endpoints
Redoc
Beautiful API documentation:
npm install redoc-cli
npx redoc-cli serve openapi.yaml
Client Generation
Generate typed API clients:
# TypeScript client
npx openapi-typescript-codegen --input openapi.yaml --output ./src/apiPython client
openapi-generator generate -i openapi.yaml -g python -o ./clientGo client
openapi-generator generate -i openapi.yaml -g go -o ./client
API Gateway Integration
Import to cloud providers:
# AWS API Gateway
aws apigateway import-rest-api --body file://openapi.yamlGoogle Cloud Endpoints
gcloud endpoints services deploy openapi.yamlKong Gateway
deck sync --spec openapi.yaml
Advanced Features
Versioned Documentation
"Generate API docs for v2 with changes from v1"
"Create migration guide from v1 to v2"
"Show deprecated endpoints in v2 documentation"
Multi-Language Examples
"Add Python and Go client examples"
"Include examples for curl, JavaScript, and Ruby"
Interactive Examples
"Generate Swagger UI compatible spec"
"Create Stoplight-compatible documentation"
Documenting Your API's Auth Requirements
These are example prompts for documenting *your API's* security β the skill itself needs no credentials:
"Document the OAuth 2.0 authentication flow for the API"
"Add API key usage instructions to the docs"
"Describe JWT token validation in the authentication section"
Troubleshooting
Issue: Missing endpoint documentation
Cause: Route not detected or commented out.
Solution:
Issue: Incorrect parameter types
Cause: Missing TypeScript types or validation schemas.
Solution:
"Regenerate docs using Zod schema for type information"
Add explicit types:
interface CreateUserRequest {
email: string;
name: string;
}router.post('/users', async (req: Request<{}, {}, CreateUserRequest>, res) => {
// ...
});
Issue: Examples are not realistic
Cause: No example data in code.
Solution: Add JSDoc examples:
/**
* @example
* {
* "email": "realistic@example.com",
* "name": "Jane Smith"
* }
*/
Issue: Authentication not documented
Cause: Middleware not detected.
Solution: Add explicit comments:
/**
* @auth bearer
* @scope users:write
*/
router.post('/users', authMiddleware, handler);
Output Formats
Markdown
OpenAPI 3.0 (YAML/JSON)
HTML
Postman Collection
Real-World Use Cases
Startup API Launch
Before:
After (with this skill):
Microservices Documentation
Challenge: 20+ internal APIs, no central docs
Solution:
"Generate API catalog for all microservices in services/"
Result:
Public API Productization
Goal: Launch developer platform
Process: 1. Generate comprehensive docs 2. Add interactive examples 3. Create client SDKs from OpenAPI 4. Deploy Swagger UI 5. Set up API gateway with spec
Outcome: API adoption 3Γ higher than manual docs
Best Practices for API Design
While documenting, consider these principles:
RESTful Conventions
/users not /getUsers/users not /user/users/:id/postsConsistent Naming
Versioning
/v1/usersAccept: application/vnd.api.v1+jsonRelated Resources
Pro Tip: Generate docs early and often. Having documentation as you build helps you design better APIs and catches inconsistencies before they ship!
License: MIT-0 (Public Domain)
βοΈ Configuration
Specify Output Format
"Generate Markdown API documentation"
"Create OpenAPI 3.0 specification in YAML"
"Generate both Markdown docs and OpenAPI spec"
"Create Postman collection from this API"
Customize Documentation Style
"Generate API docs in README format"
"Create comprehensive API reference with all examples"
"Generate minimal API docs (endpoints and parameters only)"
Include/Exclude Sections
"Generate API docs without rate limiting info"
"Include authentication details in the documentation"
"Add TypeScript client examples to the docs"
π Tips & Best Practices
For Best Results
1. Add JSDoc comments: Claude uses them for descriptions 2. Use TypeScript types: Better schema generation 3. Define validation schemas: Zod, Joi, class-validator 4. Document auth requirements: Comment with @auth tags 5. Include examples in code: Sample data helps generate realistic examples 6. Group related endpoints: Organize by resource (users, posts, etc.)
Documentation Quality Checklist
Ensure generated docs include:
Keeping Docs Updated
# Regenerate after API changes
"Regenerate API documentation after recent changes"Compare versions
"Show API changes between v1 and v2"Generate changelog
"Create API changelog from code changes"