Install
openclaw skills install api-doc-builderGenerate comprehensive API documentation from code with examples, types, and OpenAPI specs
openclaw skills install api-doc-builderNo 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.
This skill analyzes your API code and generates complete documentation including:
Supports multiple frameworks and languages:
Writing API documentation manually is tedious:
Regenerating is fast, so docs can follow code more closely:
Well-documented APIs are used more:
Generated OpenAPI specs enable:
Use this skill whenever you need API documentation:
For each endpoint:
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 API
## Endpoints
### 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 |
|---|---|---|---|---|
| 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):
{
"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
{
"error": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
401 Unauthorized - Missing or invalid authentication
{
"error": "Authentication required"
}
429 Too Many Requests - Rate limit exceeded
{
"error": "Rate limit exceeded",
"retryAfter": 45
}
Example Request:
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):
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);
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):
{
"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
{
"error": "User not found"
}
Example Request:
curl https://api.example.com/users/550e8400-e29b-41d4-a716-446655440000
Example Request (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:**
```yaml
openapi: 3.0.0
info:
title: Users API
version: 1.0.0
description: User management endpoints
servers:
- 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
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:
Your code:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
app = 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.
"Generate Markdown API documentation"
"Create OpenAPI 3.0 specification in YAML"
"Generate both Markdown docs and OpenAPI spec"
"Create Postman collection from this API"
"Generate API docs in README format"
"Create comprehensive API reference with all examples"
"Generate minimal API docs (endpoints and parameters only)"
"Generate API docs without rate limiting info"
"Include authentication details in the documentation"
"Add TypeScript client examples to the docs"
Ensure generated docs include:
# 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"
Host interactive API docs:
npm install swagger-ui-express
# server.ts
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './openapi.json';
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Import OpenAPI spec:
Beautiful API documentation:
npm install redoc-cli
npx redoc-cli serve openapi.yaml
Generate typed API clients:
# TypeScript client
npx openapi-typescript-codegen --input openapi.yaml --output ./src/api
# Python client
openapi-generator generate -i openapi.yaml -g python -o ./client
# Go client
openapi-generator generate -i openapi.yaml -g go -o ./client
Import to cloud providers:
# AWS API Gateway
aws apigateway import-rest-api --body file://openapi.yaml
# Google Cloud Endpoints
gcloud endpoints services deploy openapi.yaml
# Kong Gateway
deck sync --spec openapi.yaml
"Generate API docs for v2 with changes from v1"
"Create migration guide from v1 to v2"
"Show deprecated endpoints in v2 documentation"
"Add Python and Go client examples"
"Include examples for curl, JavaScript, and Ruby"
"Generate Swagger UI compatible spec"
"Create Stoplight-compatible documentation"
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"
Cause: Route not detected or commented out.
Solution:
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) => {
// ...
});
Cause: No example data in code.
Solution: Add JSDoc examples:
/**
* @example
* {
* "email": "realistic@example.com",
* "name": "Jane Smith"
* }
*/
Cause: Middleware not detected.
Solution: Add explicit comments:
/**
* @auth bearer
* @scope users:write
*/
router.post('/users', authMiddleware, handler);
Before:
After (with this skill):
Challenge: 20+ internal APIs, no central docs
Solution:
"Generate API catalog for all microservices in services/"
Result:
Goal: Launch developer platform
Process:
Outcome: API adoption 3× higher than manual docs
While documenting, consider these principles:
/users not /getUsers/users not /user/users/:id/posts/v1/usersAccept: application/vnd.api.v1+jsonPro 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)