Metadata-Version: 2.4
Name: drf-api-doc-generator
Version: 3.0.3
Summary: Auto-generate production-quality API & WebSocket documentation (PDF, HTML, JSON/OpenAPI) for Django REST Framework with a single command
Author-email: Ashiq <your-email@example.com>
License: MIT
Project-URL: Homepage, https://github.com/yourusername/drf-api-doc-generator
Project-URL: Documentation, https://github.com/yourusername/drf-api-doc-generator#readme
Project-URL: Repository, https://github.com/yourusername/drf-api-doc-generator
Project-URL: Issues, https://github.com/yourusername/drf-api-doc-generator/issues
Project-URL: Changelog, https://github.com/yourusername/drf-api-doc-generator/blob/main/CHANGELOG.md
Keywords: django,rest,api,documentation,swagger,openapi,pdf,drf,django-rest-framework,api-docs,auto-documentation,developer-tools,websocket,django-channels,realtime
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 3.2
Classifier: Framework :: Django :: 4.0
Classifier: Framework :: Django :: 4.1
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Documentation
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Documentation
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=3.2
Requires-Dist: djangorestframework>=3.12
Requires-Dist: reportlab>=4.0
Requires-Dist: Pillow>=9.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-django>=4.5; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: flake8>=6.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Dynamic: license-file

# DRF API & WebSocket Documentation Generator

[![PyPI version](https://badge.fury.io/py/drf-api-doc-generator.svg)](https://badge.fury.io/py/drf-api-doc-generator)
[![Python Versions](https://img.shields.io/pypi/pyversions/drf-api-doc-generator.svg)](https://pypi.org/project/drf-api-doc-generator/)
[![Django Versions](https://img.shields.io/badge/Django-3.2%20%7C%204.0%20%7C%204.1%20%7C%204.2%20%7C%205.0-blue)](https://www.djangoproject.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/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

```bash
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:

```bash
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

```python
# settings.py

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

### 2. Generate REST API Documentation

```bash
# 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

```bash
# 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

```bash
python manage.py generate_api_docs [OPTIONS] [APPS...]
```

| Option | Short | Description |
|--------|-------|-------------|
| `--all` | | Generate docs for all installed apps |
| `--websocket` | `-ws` | Path(s) to WebSocket consumer files |
| `--format` | `-f` | Output format: `pdf`, `html`, `json`, or `all` (default: `pdf`) |
| `--output` | `-o` | Output directory (default: `./api_docs/`) |
| `--title` | | Custom documentation title |
| `--api-version` | | API version string |
| `--description` | | API description |
| `--ws-base-url` | | WebSocket base URL (default: `ws://domain`) |
| `--open` | | Open file after generation |
| `-v 2` | | Verbose output (show all endpoints) |

### Examples

```bash
# 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:**
```javascript
const ws = new WebSocket('ws://domain/ws/dm/123/?token=YOUR_JWT_TOKEN');
```

**Server Response (on success):**
```json
{
  "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:

```python
# 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

```python
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

```python
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.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## 📝 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

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

---

## 📧 Support

- 📖 [Documentation](https://github.com/yourusername/drf-api-doc-generator#readme)
- 🐛 [Issue Tracker](https://github.com/yourusername/drf-api-doc-generator/issues)
- 💬 [Discussions](https://github.com/yourusername/drf-api-doc-generator/discussions)

---

**Made with ❤️ for Django developers**
