πŸš€ Big News:Socket Has Acquired Secure Annex.Learn More β†’
Socket
Book a DemoSign in
Socket

drf-api-doc-generator

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

drf-api-doc-generator

Auto-generate production-quality API & WebSocket documentation (PDF, HTML, JSON/OpenAPI) for Django REST Framework with a single command

pipPyPI
Version
1.0.0
Maintainers
1

DRF API & WebSocket Documentation Generator

PyPI version Python Versions Django Versions License: MIT

Auto-generate production-quality API & WebSocket documentation for Django REST Framework with a single command! πŸš€

Stop manually writing API documentation! This tool automatically discovers your DRF endpoints, serializers, authentication, permissions, and WebSocket consumers, then generates beautiful documentation in PDF, HTML, or OpenAPI JSON format.

✨ Features

REST API Documentation

  • πŸ“„ PDF Documentation - Professional multi-page PDF with cover page, TOC, and detailed endpoints
  • 🌐 HTML Documentation - Interactive docs with sidebar navigation and syntax highlighting
  • πŸ“‹ OpenAPI 3.0 JSON - Swagger UI and Postman compatible specification
  • πŸ” Auto-Discovery - Automatically finds all API endpoints from your URL patterns
  • 🎯 Serializer Extraction - Extracts field types, validations, and descriptions
  • πŸ” Auth Detection - Documents authentication and permission requirements

πŸ”Œ WebSocket Documentation (NEW!)

  • πŸ“‘ Consumer Parsing - Automatically parses Django Channels consumers
  • πŸ”„ Action Handlers - Documents all client-to-server actions
  • πŸ“¨ Server Events - Documents server-to-client broadcast events
  • πŸ”— Connection Lifecycle - Documents connect/disconnect flow with error codes
  • πŸ’‘ Example Messages - Auto-generates example request/response JSON
  • 🎨 Syntax Highlighting - Beautiful code blocks with proper highlighting

πŸ“¦ Installation

pip install drf-api-doc-generator

πŸš€ Quick Start

πŸš€ Quick Share (Magic Command)

Generate complete documentation for all apps and WebSockets, zipped and ready to share:

python manage.py generate_api_docs complete-project-zip-html

This single command will:

  • Auto-discover all Django Apps
  • Auto-discover all consumers.py (WebSocket) files
  • Generate HTML documentation
  • Create a ZIP package for easy sharing

πŸ“š Detailed Usage

1. Add to INSTALLED_APPS

# settings.py

INSTALLED_APPS = [
    # ... your other apps
    'rest_framework',
    'api_docs_generator',  # Add this line
]

2. Generate REST API Documentation

# Generate PDF for a specific app
python manage.py generate_api_docs auth

# Generate for multiple apps
python manage.py generate_api_docs auth users products

# Generate all formats (PDF + HTML + JSON)
python manage.py generate_api_docs auth --format all

# Generate for all apps
python manage.py generate_api_docs --all

3. Generate WebSocket Documentation

# Document a WebSocket consumer file
python manage.py generate_api_docs --websocket chat/consumers/dm_consumer.py

# Document multiple WebSocket files
python manage.py generate_api_docs --websocket chat/consumers/*.py

# Combine REST API and WebSocket documentation
python manage.py generate_api_docs auth --websocket chat/consumers/dm_consumer.py --format all

4. Find Your Docs

Documentation will be generated in ./api_docs/ directory:

  • api_docs_YYYYMMDD_HHMMSS.pdf
  • api_docs_YYYYMMDD_HHMMSS.html
  • api_docs_YYYYMMDD_HHMMSS.json

πŸ“– Command Options

python manage.py generate_api_docs [OPTIONS] [APPS...]
OptionShortDescription
--allGenerate docs for all installed apps
--websocket-wsPath(s) to WebSocket consumer files
--format-fOutput format: pdf, html, json, or all (default: pdf)
--output-oOutput directory (default: ./api_docs/)
--titleCustom documentation title
--api-versionAPI version string
--descriptionAPI description
--ws-base-urlWebSocket base URL (default: ws://domain)
--openOpen file after generation
-v 2Verbose output (show all endpoints)

Examples

# Generate PDF with custom title
python manage.py generate_api_docs auth --title "My Awesome API"

# Generate with WebSocket and custom base URL
python manage.py generate_api_docs --websocket chat/consumers.py --ws-base-url wss://api.myapp.com

# Generate to custom directory
python manage.py generate_api_docs auth --output ./docs/api/

# Generate and open automatically
python manage.py generate_api_docs auth --format html --open

# Verbose mode - show all discovered endpoints
python manage.py generate_api_docs auth -v 2

πŸ”Œ WebSocket Documentation Format

The generated documentation for WebSocket consumers includes:

Connection Lifecycle

Client Action:

const ws = new WebSocket('ws://domain/ws/dm/123/?token=YOUR_JWT_TOKEN');

Server Response (on success):

{
  "type": "connection_established",
  "user_id": 123,
  "timestamp": "2025-01-15T10:30:00.000Z"
}

Client Actions

Each action includes:

  • Action name and description
  • Request schema/example
  • Response/broadcast example

Server Events

Events broadcast from server to clients:

  • Event type and description
  • Payload example

βš™οΈ Configuration

Add optional configuration to your Django settings:

# settings.py

API_DOCS_CONFIG = {
    'TITLE': 'My API Documentation',
    'VERSION': '2.0.0',
    'DESCRIPTION': 'Complete API reference for developers',
    'CONTACT_EMAIL': 'api@example.com',
    'LOGO_PATH': 'path/to/logo.png',  # Optional logo for PDF cover
    'THEME_COLOR': '#2563eb',  # Primary theme color
    'WS_BASE_URL': 'wss://api.example.com',  # WebSocket base URL
}

πŸ“Š What Gets Documented?

From REST Views/ViewSets:

  • βœ… URL paths and patterns
  • βœ… HTTP methods (GET, POST, PUT, PATCH, DELETE)
  • βœ… View docstrings as descriptions
  • βœ… Authentication classes
  • βœ… Permission classes

From Serializers:

  • βœ… Field names and types
  • βœ… Required/optional status
  • βœ… Read-only/write-only fields
  • βœ… Field help text
  • βœ… Choices/enums
  • βœ… Validation constraints

From WebSocket Consumers:

  • βœ… Connection URL pattern
  • βœ… Connection parameters (from URL)
  • βœ… Connection response schema
  • βœ… Disconnect/error codes
  • βœ… Action handlers (client β†’ server)
  • βœ… Server events (server β†’ client)
  • βœ… Message schemas and examples
  • βœ… Features from docstrings

πŸ’‘ Tips for Better WebSocket Documentation

1. Add Docstrings to Consumers

class DMConsumer(AsyncJsonWebsocketConsumer):
    """
    DM Consumer

    Features:
    - Lazy conversation creation (only on first message)
    - Anyone can message anyone (unknown users allowed)
    - Spam protection for unknown users
    - Typing & recording indicators
    - Read receipts
    """
    pass

2. Document Action Handlers

async def handle_send_message(self, content):
    """
    Send message

    Client sends:
    {
        "action": "send_message",
        "content": "message text",
        "msg_type": "text"
    }
    """
    pass

3. Use Clear Handler Naming

Name your handlers with handle_ prefix:

  • handle_send_message
  • handle_typing_start
  • handle_mark_read

πŸ“„ Output Formats

PDF

Professional documentation with:

  • Cover page with title, version, and generation date
  • Table of contents
  • Detailed endpoint documentation
  • Syntax-highlighted code examples
  • Clean, user-friendly design

HTML

Interactive documentation with:

  • Light theme UI
  • Sidebar navigation
  • Syntax-highlighted JSON/JS examples
  • Method badges (GET=green, POST=blue, WS=cyan)
  • Responsive design

JSON (OpenAPI 3.0)

Standard specification compatible with:

  • Swagger UI
  • Postman
  • Redoc
  • OpenAPI Generator

πŸ”§ Requirements

  • Python 3.8+
  • Django 3.2+
  • Django REST Framework 3.12+
  • ReportLab 4.0+ (for PDF generation)
  • Pillow 9.0+ (for image handling)

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  • Fork the repository
  • Create your feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Built for the Django REST Framework & Channels community
  • Inspired by Swagger/OpenAPI specification
  • PDF generation powered by ReportLab

πŸ“§ Support

Made with ❀️ for Django developers

Keywords

django

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts