Skip to content

API Documentation Generator Command

Generate API documentation from code

Instructions

Follow this systematic approach to create API documentation: $ARGUMENTS

  1. Code Analysis and Discovery
  2. Scan the codebase for API endpoints, routes, and handlers
  3. Identify REST APIs, GraphQL schemas, and RPC services
  4. Map out controller classes, route definitions, and middleware
  5. Discover request/response models and data structures

  6. Documentation Tool Selection

  7. 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
  8. 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

  1. Endpoint Documentation
  2. Document all HTTP methods (GET, POST, PUT, DELETE, PATCH)
  3. Specify request parameters (path, query, header, body)
  4. Define response schemas and status codes
  5. Include error responses and error codes
  6. Document authentication and authorization requirements

  7. Request/Response Examples

  8. Provide realistic request examples for each endpoint
  9. Include sample response data with proper formatting
  10. Show different response scenarios (success, error, edge cases)
  11. Document content types and encoding

  12. Authentication Documentation

  13. Document authentication methods (API keys, JWT, OAuth)
  14. Explain authorization scopes and permissions
  15. Provide authentication examples and token formats
  16. Document session management and refresh token flows

  17. Data Model Documentation

  18. Define all data schemas and models
  19. Document field types, constraints, and validation rules
  20. Include relationships between entities
  21. Provide example data structures

  22. Error Handling Documentation

  23. Document all possible error responses
  24. Explain error codes and their meanings
  25. Provide troubleshooting guidance
  26. Include rate limiting and throttling information

  27. 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>

  1. 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
  2. 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));
    

  3. 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
  4. Version Management

    • Document API versioning strategy
    • Maintain documentation for multiple API versions
    • Document deprecation timelines and migration guides
    • Track breaking changes between versions
  5. Performance Documentation

    • Document rate limits and throttling policies
    • Include performance benchmarks and SLAs
    • Document caching strategies and headers
    • Explain pagination and filtering options
  6. 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
  7. Environment-Specific Documentation

    • Document different environments (dev, staging, prod)
    • Include environment-specific endpoints and configurations
    • Document deployment and configuration requirements
    • Provide environment setup instructions
  8. Security Documentation

    • Document security best practices
    • Include CORS and CSP policies
    • Document input validation and sanitization
    • Explain security headers and their purposes
  9. 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.