bytedocs-fastapi 0.1.2
Alternative to Swagger with better design, auto-detection, and AI integration
Requires Python: >=3.8
Keywords: fastapi, documentation, api, swagger, openapi, bytedocs, auto-documentation, api-doc, rest-api, python

# ByteDocs FastAPI

Automatic API documentation generator for FastAPI - inspired by Scramble for Laravel and based on ByteDocs Express.

> **Note**: This is a **Python package/library**, not a standalone application. You install it in your FastAPI project, and it adds documentation endpoints to **your** application.

## Features

- 🚀 **Automatic Route Detection** - Detects all FastAPI routes, endpoints, and handlers
- 📝 **Request/Response Analysis** - Automatically extracts Pydantic models for request bodies and response schemas
- 🎨 **Beautiful UI** - Modern, responsive documentation interface
- 🔐 **Authentication Support** - Multiple auth methods (Basic, API Key, Bearer, Session)
- 🌍 **Multi-Environment** - Support for multiple base URLs (development, staging, production)
- 📤 **OpenAPI Export** - Export documentation as OpenAPI 3.0 JSON/YAML
- 🎯 **Zero Configuration** - Works out of the box with sensible defaults
- ⚙️ **Highly Configurable** - Customize everything via config or environment variables

## Installation

```bash
pip install bytedocs-fastapi
```

## Quick Start

> **⚠️ IMPORTANT**: You **must** disable FastAPI's default Swagger UI to use ByteDocs. FastAPI uses `/docs` by default, so we need to disable it first.

```python
from fastapi import FastAPI
from bytedocs_fastapi import setup_bytedocs

# REQUIRED: Disable FastAPI's built-in Swagger/ReDoc
app = FastAPI(
    docs_url=None,      # ← REQUIRED: Disable default Swagger UI
    redoc_url=None,     # ← REQUIRED: Disable default ReDoc
    openapi_url=None    # ← REQUIRED: Disable default OpenAPI (ByteDocs provides this)
)

# Setup ByteDocs with minimal config
setup_bytedocs(app, {
    "title": "My API",
    "version": "1.0.0",
    "description": "My awesome API documentation",
})

# Your routes
@app.get("/users")
async def get_users():
    return {"users": []}

@app.post("/users")
async def create_user(user: UserModel):
    return {"user": user}
```

Run your FastAPI application:

```bash
uvicorn main:app --reload
```

Visit `http://localhost:8000/docs` to see your documentation!

**What happens**:
- ByteDocs automatically detects all your routes
- Adds `/docs` endpoint to **your** FastAPI app (replacing the default Swagger)
- Documentation is generated from your Pydantic models and route definitions

### Why Disable Default Swagger?

FastAPI comes with built-in Swagger UI at `/docs` by default. ByteDocs also uses `/docs` for its documentation UI, so you need to disable FastAPI's default to avoid conflicts.

**Without disabling:**
```python
app = FastAPI()  # ❌ This will use FastAPI's default Swagger, not ByteDocs!
```

**With disabling (correct):**
```python
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)  # ✅ Now ByteDocs can use /docs
```

## Configuration

### Via Code

```python
from bytedocs_fastapi import setup_bytedocs, ByteDocsConfig, AuthConfig

config = {
    "title": "My API",
    "version": "1.0.0",
    "description": "API Documentation",
    "base_url": "http://localhost:8000",
    "docs_path": "/docs",
    "auto_detect": True,
    "exclude_paths": ["/health", "/metrics"],
    "auth_config": {
        "enabled": True,
        "type": "session",
        "password": "your-secret-password",
    },
    "ui_config": {
        "theme": "blue",
        "dark_mode": False,
    },
}

setup_bytedocs(app, config)
```

### Via Environment Variables

```bash
BYTEDOCS_TITLE="My API"
BYTEDOCS_VERSION="1.0.0"
BYTEDOCS_DESCRIPTION="API Documentation"
BYTEDOCS_BASE_URL="http://localhost:8000"
BYTEDOCS_DOCS_PATH="/docs"
BYTEDOCS_AUTO_DETECT="true"
BYTEDOCS_EXCLUDE_PATHS="/health,/metrics"

# Authentication
BYTEDOCS_AUTH_ENABLED="true"
BYTEDOCS_AUTH_TYPE="session"
BYTEDOCS_AUTH_PASSWORD="your-secret-password"

# UI
BYTEDOCS_UI_THEME="blue"
BYTEDOCS_UI_DARK_MODE="false"
```

## Authentication

ByteDocs FastAPI supports multiple authentication methods:

### Session-based Auth

```python
config = {
    "auth_config": {
        "enabled": True,
        "type": "session",
        "password": "your-secret-password",
        "session_expire": 60,  # minutes
    }
}
```

### Basic Auth

```python
config = {
    "auth_config": {
        "enabled": True,
        "type": "basic",
        "username": "admin",
        "password": "secret",
    }
}
```

### API Key Auth

```python
config = {
    "auth_config": {
        "enabled": True,
        "type": "api_key",
        "api_key": "your-api-key",
        "api_key_header": "X-API-Key",
    }
}
```

## Advanced Usage

### Multiple Base URLs

```python
config = {
    "base_urls": [
        {"name": "Development", "url": "http://localhost:8000"},
        {"name": "Staging", "url": "https://staging.api.example.com"},
        {"name": "Production", "url": "https://api.example.com"},
    ]
}
```

### Manual Route Registration

```python
from bytedocs_fastapi import ByteDocs, RouteInfo

bytedocs = ByteDocs(config)

# Manually add a route
bytedocs.add_route(RouteInfo(
    method="GET",
    path="/custom",
    handler=my_handler,
    summary="Custom endpoint",
    description="This is a custom endpoint",
))

bytedocs.generate()
bytedocs.setup_fastapi(app)
```

## Pydantic Model Detection

ByteDocs automatically detects and documents Pydantic models:

```python
from pydantic import BaseModel, Field

class UserCreate(BaseModel):
    name: str = Field(..., description="User's full name")
    email: str = Field(..., description="User's email address")
    age: int = Field(ge=0, le=150, description="User's age")

class UserResponse(BaseModel):
    id: int
    name: str
    email: str
    created_at: str

@app.post("/users", response_model=UserResponse)
async def create_user(user: UserCreate):
    # ByteDocs will automatically document both models
    return UserResponse(
        id=1,
        name=user.name,
        email=user.email,
        created_at="2024-01-01T00:00:00Z"
    )
```

## Endpoints

ByteDocs adds these endpoints to your FastAPI app:

- `GET /docs` - Documentation UI
- `GET /docs/api-data.json` - API data in JSON format
- `GET /docs/openapi.json` - OpenAPI 3.0 specification (JSON)
- `GET /docs/openapi.yaml` - OpenAPI 3.0 specification (YAML)

## UI Themes

Available themes: `green`, `blue`, `purple`, `red`, `orange`, `teal`, `pink`

```python
config = {
    "ui_config": {
        "theme": "purple",
        "dark_mode": True,
    }
}
```

## Examples

The `examples/` folder contains sample applications showing how to use ByteDocs FastAPI. These are **not** part of the installed package - they're just reference implementations.

### Running the Example App

#### Quick Start (Using Helper Scripts):

```bash
# Clone the repository (for development)
git clone <repo-url>
cd bytedocs-fastapi

# Setup development environment
./setup_dev.sh

# Run the example
./run_example.sh

# Or run tests
./run_tests.sh
```

#### Manual Setup:

```bash
# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install package in development mode
pip install -e .
pip install uvicorn

# Run the example
python examples/basic/main.py

# Or using venv directly without activation
./venv/bin/python examples/basic/main.py
```

Then visit http://localhost:8000/docs

**Note**: When users install via `pip install bytedocs-fastapi`, they don't get the examples folder. They create their own FastAPI app and use the package.

## Package vs Application

### This Package Provides:
- ✅ Python library (`bytedocs_fastapi`)
- ✅ Functions to integrate with your FastAPI app
- ✅ UI templates for documentation
- ✅ Route detection and OpenAPI generation

### This Package Does NOT Provide:
- ❌ A standalone server
- ❌ A ready-to-run application
- ❌ Pre-defined routes

### How It Works:
1. You create your FastAPI application
2. You call `setup_bytedocs(app)` in your code
3. ByteDocs adds `/docs` endpoints to **your** application
4. You run **your** application with uvicorn
5. Documentation appears at **your** `/docs` URL

## License

MIT License - see LICENSE file for details

## Contributing

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

## Credits

- Inspired by [Scramble](https://scramble.dedoc.co/) for Laravel
- Based on [ByteDocs Express](https://github.com/idnexacloud/bytedocs-express)