API Documentation Generator
Generate API documentation from code: $ARGUMENTS
Current API Context
- API endpoints: !
find . -name "*route*" -o -name "*controller*" -o -name "*api*" | head -5
- API specs: !
find . -name "*openapi*" -o -name "*swagger*" -o -name "*.graphql" | head -3
- Server framework: @package.json or detect from imports
- Existing docs: @docs/api/ or @api-docs/ (if exists)
- Test files: !
find . -name "*test*" -path "*/api/*" | head -3
Task
Generate comprehensive API documentation with interactive features: $ARGUMENTS
Code Analysis and Discovery
- Scan the codebase for API endpoints, routes, and handlers
- Identify REST APIs, GraphQL schemas, and RPC services
- Map out controller classes, route definitions, and middleware
- Discover request/response models and data structures
Documentation Tool Selection
- Choose appropriate documentation tools based on stack:
- OpenAPI/Swagger: REST APIs with interactive documentation
- GraphQL: GraphiQL, GraphQL Playground, or Apollo Studio
- Postman: API collections and documentation
- Insomnia: API design and documentation
- Redoc: Alternative OpenAPI renderer
- API Blueprint: Markdown-based API documentation
API Specification Generation
For REST APIs with OpenAPI:
openapi: 3.0.0
info:
title: $ARGUMENTS API
version: 1.0.0
description: Comprehensive API for $ARGUMENTS
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: List users
parameters:
- name: page
in: query
schema:
type: integer
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
Endpoint Documentation
- Document all HTTP methods (GET, POST, PUT, DELETE, PATCH)
- Specify request parameters (path, query, header, body)
- Define response schemas and status codes
- Include error responses and error codes
- Document authentication and authorization requirements
Request/Response Examples
- Provide realistic request examples for each endpoint
- Include sample response data with proper formatting
- Show different response scenarios (success, error, edge cases)
- Document content types and encoding
Authentication Documentation
- Document authentication methods (API keys, JWT, OAuth)
- Explain authorization scopes and permissions
- Provide authentication examples and token formats
- Document session management and refresh token flows
Data Model Documentation
- Define all data schemas and models
- Document field types, constraints, and validation rules
- Include relationships between entities
- Provide example data structures
Error Handling Documentation
- Document all possible error responses
- Explain error codes and their meanings
- Provide troubleshooting guidance
- Include rate limiting and throttling information
Interactive Documentation Setup
Swagger UI Integration:
<!DOCTYPE html>
<html>
<head>
<title>API Documentation</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui-bundle.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: './api-spec.yaml',
dom_id: '#swagger-ui'
});
</script>
</body>
</html>
Code Annotation and Comments
- Add inline documentation to API handlers
- Use framework-specific annotation tools:
- Java: @ApiOperation, @ApiParam (Swagger annotations)
- Python: Docstrings with FastAPI or Flask-RESTX
- Node.js: JSDoc comments with swagger-jsdoc
- C#: XML documentation comments
Automated Documentation Generation
For Node.js/Express:
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'API Documentation',
version: '1.0.0',
},
},
apis: ['./routes/*.js'],
};
const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
Testing Integration
- Generate API test collections from documentation
- Include test scripts and validation rules
- Set up automated API testing
- Document test scenarios and expected outcomes
Version Management
- Document API versioning strategy
- Maintain documentation for multiple API versions
- Document deprecation timelines and migration guides
- Track breaking changes between versions
Performance Documentation
- Document rate limits and throttling policies
- Include performance benchmarks and SLAs
- Document caching strategies and headers
- Explain pagination and filtering options
SDK and Client Library Documentation
- Generate client libraries from API specifications
- Document SDK usage and examples
- Provide quickstart guides for different languages
- Include integration examples and best practices
Environment-Specific Documentation
- Document different environments (dev, staging, prod)
- Include environment-specific endpoints and configurations
- Document deployment and configuration requirements
- Provide environment setup instructions
Security Documentation
- Document security best practices
- Include CORS and CSP policies
- Document input validation and sanitization
- Explain security headers and their purposes
Maintenance and Updates
- Set up automated documentation updates
- Create processes for keeping documentation current
- Review and validate documentation regularly
- Integrate documentation reviews into development workflow
Framework-Specific Examples:
FastAPI (Python):
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="My API", version="1.0.0")
class User(BaseModel):
id: int
name: str
email: str
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
"""Get a user by ID."""
return {"id": user_id, "name": "John", "email": "john@example.com"}
Spring Boot (Java):
@RestController
@Api(tags = "Users")
public class UserController {
@GetMapping("/users/{id}")
@ApiOperation(value = "Get user by ID")
public ResponseEntity<User> getUser(
@PathVariable @ApiParam("User ID") Long id) {
// Implementation
}
}
Remember to keep documentation up-to-date with code changes and make it easily accessible to both internal teams and external consumers.
1---2name: 1790-doc-api-7e76ec7d3description: API Documentation Generator4---56# API Documentation Generator78Generate API documentation from code: $ARGUMENTS910## Current API Context1112- API endpoints: !`find . -name "*route*" -o -name "*controller*" -o -name "*api*" | head -5`13- API specs: !`find . -name "*openapi*" -o -name "*swagger*" -o -name "*.graphql" | head -3`14- Server framework: @package.json or detect from imports15- Existing docs: @docs/api/ or @api-docs/ (if exists)16- Test files: !`find . -name "*test*" -path "*/api/*" | head -3`1718## Task1920Generate comprehensive API documentation with interactive features: $ARGUMENTS21221. **Code Analysis and Discovery**23 - Scan the codebase for API endpoints, routes, and handlers24 - Identify REST APIs, GraphQL schemas, and RPC services25 - Map out controller classes, route definitions, and middleware26 - Discover request/response models and data structures27282. **Documentation Tool Selection**29 - Choose appropriate documentation tools based on stack:30 - **OpenAPI/Swagger**: REST APIs with interactive documentation31 - **GraphQL**: GraphiQL, GraphQL Playground, or Apollo Studio32 - **Postman**: API collections and documentation33 - **Insomnia**: API design and documentation34 - **Redoc**: Alternative OpenAPI renderer35 - **API Blueprint**: Markdown-based API documentation36373. **API Specification Generation**38 39 **For REST APIs with OpenAPI:**40 ```yaml41 openapi: 3.0.042 info:43 title: $ARGUMENTS API44 version: 1.0.045 description: Comprehensive API for $ARGUMENTS46 servers:47 - url: https://api.example.com/v148 paths:49 /users:50 get:51 summary: List users52 parameters:53 - name: page54 in: query55 schema:56 type: integer57 responses:58 '200':59 description: Successful response60 content:61 application/json:62 schema:63 type: array64 items:65 $ref: '#/components/schemas/User'66 components:67 schemas:68 User:69 type: object70 properties:71 id:72 type: integer73 name:74 type: string75 email:76 type: string77 ```78794. **Endpoint Documentation**80 - Document all HTTP methods (GET, POST, PUT, DELETE, PATCH)81 - Specify request parameters (path, query, header, body)82 - Define response schemas and status codes83 - Include error responses and error codes84 - Document authentication and authorization requirements85865. **Request/Response Examples**87 - Provide realistic request examples for each endpoint88 - Include sample response data with proper formatting89 - Show different response scenarios (success, error, edge cases)90 - Document content types and encoding91926. **Authentication Documentation**93 - Document authentication methods (API keys, JWT, OAuth)94 - Explain authorization scopes and permissions95 - Provide authentication examples and token formats96 - Document session management and refresh token flows97987. **Data Model Documentation**99 - Define all data schemas and models100 - Document field types, constraints, and validation rules101 - Include relationships between entities102 - Provide example data structures1031048. **Error Handling Documentation**105 - Document all possible error responses106 - Explain error codes and their meanings107 - Provide troubleshooting guidance108 - Include rate limiting and throttling information1091109. **Interactive Documentation Setup**111 112 **Swagger UI Integration:**113 ```html114 <!DOCTYPE html>115 <html>116 <head>117 <title>API Documentation</title>118 <link rel="stylesheet" type="text/css" href="./swagger-ui-bundle.css" />119 </head>120 <body>121 <div id="swagger-ui"></div>122 <script src="./swagger-ui-bundle.js"></script>123 <script>124 SwaggerUIBundle({125 url: './api-spec.yaml',126 dom_id: '#swagger-ui'127 });128 </script>129 </body>130 </html>131 ```13213310. **Code Annotation and Comments**134 - Add inline documentation to API handlers135 - Use framework-specific annotation tools:136 - **Java**: @ApiOperation, @ApiParam (Swagger annotations)137 - **Python**: Docstrings with FastAPI or Flask-RESTX138 - **Node.js**: JSDoc comments with swagger-jsdoc139 - **C#**: XML documentation comments14014111. **Automated Documentation Generation**142 143 **For Node.js/Express:**144 ```javascript145 const swaggerJsdoc = require('swagger-jsdoc');146 const swaggerUi = require('swagger-ui-express');147 148 const options = {149 definition: {150 openapi: '3.0.0',151 info: {152 title: 'API Documentation',153 version: '1.0.0',154 },155 },156 apis: ['./routes/*.js'],157 };158 159 const specs = swaggerJsdoc(options);160 app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));161 ```16216312. **Testing Integration**164 - Generate API test collections from documentation165 - Include test scripts and validation rules166 - Set up automated API testing167 - Document test scenarios and expected outcomes16816913. **Version Management**170 - Document API versioning strategy171 - Maintain documentation for multiple API versions172 - Document deprecation timelines and migration guides173 - Track breaking changes between versions17417514. **Performance Documentation**176 - Document rate limits and throttling policies177 - Include performance benchmarks and SLAs178 - Document caching strategies and headers179 - Explain pagination and filtering options18018115. **SDK and Client Library Documentation**182 - Generate client libraries from API specifications183 - Document SDK usage and examples184 - Provide quickstart guides for different languages185 - Include integration examples and best practices18618716. **Environment-Specific Documentation**188 - Document different environments (dev, staging, prod)189 - Include environment-specific endpoints and configurations190 - Document deployment and configuration requirements191 - Provide environment setup instructions19219317. **Security Documentation**194 - Document security best practices195 - Include CORS and CSP policies196 - Document input validation and sanitization197 - Explain security headers and their purposes19819918. **Maintenance and Updates**200 - Set up automated documentation updates201 - Create processes for keeping documentation current202 - Review and validate documentation regularly203 - Integrate documentation reviews into development workflow204205**Framework-Specific Examples:**206207**FastAPI (Python):**208```python209from fastapi import FastAPI210from pydantic import BaseModel211212app = FastAPI(title="My API", version="1.0.0")213214class User(BaseModel):215 id: int216 name: str217 email: str218219@app.get("/users/{user_id}", response_model=User)220async def get_user(user_id: int):221 """Get a user by ID."""222 return {"id": user_id, "name": "John", "email": "john@example.com"}223```224225**Spring Boot (Java):**226```java227@RestController228@Api(tags = "Users")229public class UserController {230 231 @GetMapping("/users/{id}")232 @ApiOperation(value = "Get user by ID")233 public ResponseEntity<User> getUser(234 @PathVariable @ApiParam("User ID") Long id) {235 // Implementation236 }237}238```239240Remember to keep documentation up-to-date with code changes and make it easily accessible to both internal teams and external consumers.