fastapi-docshield


Namefastapi-docshield JSON
Version 0.2.1 PyPI version JSON
download
home_pageNone
SummaryA simple FastAPI integration to protect documentation endpoints with authentication
upload_time2025-08-17 11:39:35
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT License Copyright (c) 2025 George Khananaev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords authentication documentation fastapi security
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastAPI DocShield

A simple FastAPI integration to protect documentation endpoints with HTTP Basic Authentication.

[![PyPI version](https://badge.fury.io/py/fastapi-docshield.svg)](https://badge.fury.io/py/fastapi-docshield)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python Versions](https://img.shields.io/badge/python-3.7%20%7C%203.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/georgekhananaev/fastapi-docshield)
[![Tests Status](https://img.shields.io/badge/tests-passing-brightgreen)](https://github.com/georgekhananaev/fastapi-docshield)
[![UV Compatible](https://img.shields.io/badge/uv-compatible-blueviolet)](https://github.com/astral-sh/uv)

## About

Protect FastAPI's `/docs`, `/redoc`, and `/openapi.json` endpoints with HTTP Basic Authentication.

## Installation

### From PyPI

```bash
# Install with pip
pip install fastapi-docshield

# Or with uv
uv pip install fastapi-docshield
```

### From Source

```bash
git clone https://github.com/georgekhananaev/fastapi-docshield.git
cd fastapi-docshield
pip install -e .
```

## Quick Usage

### Single User

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# Add protection to docs with a single user
DocShield(
    app=app,
    credentials={"admin": "password123"}
)
```

### Multiple Users

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# Add protection to docs with multiple users
DocShield(
    app=app,
    credentials={
        "admin": "admin_password",
        "developer": "dev_password",
        "viewer": "viewer_password"
    }
)
```

### CDN Fallback Mode (Default)

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield

app = FastAPI()

# Default mode: Use CDN with automatic fallback to local files
DocShield(
    app=app,
    credentials={"admin": "password123"},
    use_cdn_fallback=True  # Default - automatically falls back to local if CDN fails
)
```

### Prefer Local Files

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield

app = FastAPI()

# Always use local files instead of CDN
DocShield(
    app=app,
    credentials={"admin": "password123"},
    prefer_local=True  # Serve documentation from bundled static files
)
```

### CDN Only (No Fallback)

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield

app = FastAPI()

# Use CDN without fallback (original behavior)
DocShield(
    app=app,
    credentials={"admin": "password123"},
    use_cdn_fallback=False  # Disable fallback, CDN only
)
```

### Custom CSS and JavaScript

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield
import requests

app = FastAPI()

# Load dark theme CSS from external source
# You can use https://github.com/georgekhananaev/fastapi-swagger-dark
dark_theme_url = "https://raw.githubusercontent.com/georgekhananaev/fastapi-swagger-dark/main/src/fastapi_swagger_dark/swagger_ui_dark.min.css"
custom_css = requests.get(dark_theme_url).text

# Custom JavaScript for analytics
custom_js = """
console.log('📊 Documentation accessed at:', new Date().toISOString());
document.addEventListener('DOMContentLoaded', function() {
    console.log('Dark theme loaded!');
});
"""

# Apply with custom styling
DocShield(
    app=app,
    credentials={"admin": "password123"},
    custom_css=custom_css,
    custom_js=custom_js
)
```

#### Using with fastapi-swagger-dark

For a complete dark theme solution, you can use the [fastapi-swagger-dark](https://github.com/georgekhananaev/fastapi-swagger-dark) package:

```python
from fastapi import FastAPI
from fastapi_docshield import DocShield
import requests

app = FastAPI()

# Fetch dark theme CSS
response = requests.get(
    "https://raw.githubusercontent.com/georgekhananaev/fastapi-swagger-dark/main/src/fastapi_swagger_dark/swagger_ui_dark.min.css"
)
dark_css = response.text

DocShield(
    app=app,
    credentials={"admin": "password123"},
    custom_css=dark_css  # Apply dark theme
)
```

See [examples/custom_styling.py](examples/custom_styling.py) for more customization examples including:
- ✨ Minimal clean theme
- 🏢 Corporate theme with analytics
- 📖 ReDoc customization
- 🎨 Custom branding

## Running Demo

```bash
# Run the demo app
python demo.py

# Visit http://localhost:8000/docs
# Username: admin
# Password: password123
```

## Running Tests

```bash
# Install test dependencies
pip install pytest httpx

# Run all tests
pytest

# Run with coverage
pytest --cov=fastapi_docshield
```

## Features

- Protect Swagger UI, ReDoc, and OpenAPI JSON endpoints
- Customizable endpoint URLs
- Multiple username/password combinations
- **Automatic CDN fallback** - Falls back to local files if CDN is unavailable
- **Local file preference option** - Serve documentation from local files for better reliability
- **Custom CSS and JavaScript injection** - Fully customize the look and behavior of documentation
- **Resilient documentation** - Works even when CDN is down or blocked
- Tested on Python 3.7-3.13
- Compatible with uv package manager

## Changelog

### Version 0.2.1 (2025-08-17)
- **Fixed**: Blank page issue after authentication for some users
  - Improved handling of custom URL parameters by storing them as instance variables
  - Simplified `_setup_routes()` method for better maintainability
  - Applied fix from PR #2 for more robust URL parameter handling
- **Fixed**: Route removal logic now correctly removes all default documentation routes
  - Properly removes `/docs`, `/redoc`, and `/openapi.json` endpoints
  - Prevents 500 errors when accessing old endpoints
- **Improved**: Example files and documentation
  - Fixed `custom_styling.py` to work with uvicorn by adding default app variable
  - Standardized credentials across all custom styling examples
  - Added `python-multipart` to dev dependencies for form data handling
  - Added clear run instructions in example files

### Version 0.2.0 (2025-08-17)
- **Added**: Custom CSS and JavaScript injection support
  - New `custom_css` parameter to inject custom styles into documentation pages
  - New `custom_js` parameter to inject custom JavaScript for enhanced functionality
  - Complete customization examples for dark theme, minimal theme, corporate branding, and analytics
  - Support for both Swagger UI and ReDoc customization
- **Added**: Automatic CDN fallback to local files for better reliability
  - Documentation now automatically falls back to bundled static files if CDN is unavailable
  - New `prefer_local` option to always serve from local files
  - New `use_cdn_fallback` option to control fallback behavior
  - Bundled Swagger UI and ReDoc static files for offline capability
- **Fixed**: Static file URL bug that caused blank documentation pages
  - Previously, when no custom CDN URLs were provided, the package would pass `None` values to FastAPI's documentation functions
  - This resulted in HTML with `href="None"` and `src="None"`, causing white/blank pages
  - Now properly handles default CDN URLs when custom URLs are not specified

### Version 0.1.0 (2025-01-15)
- Initial release
- Basic HTTP authentication for FastAPI documentation endpoints
- Support for multiple users

## License

MIT License - Copyright (c) 2025 George Khananaev
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-docshield",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "authentication, documentation, fastapi, security",
    "author": null,
    "author_email": "George Khananaev <georgekhananaev@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/18/6c/8aeca2c9b9b6472c4d372a29ef5b337c890e6ff4af83e2c19eb530580493/fastapi_docshield-0.2.1.tar.gz",
    "platform": null,
    "description": "# FastAPI DocShield\n\nA simple FastAPI integration to protect documentation endpoints with HTTP Basic Authentication.\n\n[![PyPI version](https://badge.fury.io/py/fastapi-docshield.svg)](https://badge.fury.io/py/fastapi-docshield)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Python Versions](https://img.shields.io/badge/python-3.7%20%7C%203.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/georgekhananaev/fastapi-docshield)\n[![Tests Status](https://img.shields.io/badge/tests-passing-brightgreen)](https://github.com/georgekhananaev/fastapi-docshield)\n[![UV Compatible](https://img.shields.io/badge/uv-compatible-blueviolet)](https://github.com/astral-sh/uv)\n\n## About\n\nProtect FastAPI's `/docs`, `/redoc`, and `/openapi.json` endpoints with HTTP Basic Authentication.\n\n## Installation\n\n### From PyPI\n\n```bash\n# Install with pip\npip install fastapi-docshield\n\n# Or with uv\nuv pip install fastapi-docshield\n```\n\n### From Source\n\n```bash\ngit clone https://github.com/georgekhananaev/fastapi-docshield.git\ncd fastapi-docshield\npip install -e .\n```\n\n## Quick Usage\n\n### Single User\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n\n# Add protection to docs with a single user\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"}\n)\n```\n\n### Multiple Users\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n\n# Add protection to docs with multiple users\nDocShield(\n    app=app,\n    credentials={\n        \"admin\": \"admin_password\",\n        \"developer\": \"dev_password\",\n        \"viewer\": \"viewer_password\"\n    }\n)\n```\n\n### CDN Fallback Mode (Default)\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\n\napp = FastAPI()\n\n# Default mode: Use CDN with automatic fallback to local files\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"},\n    use_cdn_fallback=True  # Default - automatically falls back to local if CDN fails\n)\n```\n\n### Prefer Local Files\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\n\napp = FastAPI()\n\n# Always use local files instead of CDN\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"},\n    prefer_local=True  # Serve documentation from bundled static files\n)\n```\n\n### CDN Only (No Fallback)\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\n\napp = FastAPI()\n\n# Use CDN without fallback (original behavior)\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"},\n    use_cdn_fallback=False  # Disable fallback, CDN only\n)\n```\n\n### Custom CSS and JavaScript\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\nimport requests\n\napp = FastAPI()\n\n# Load dark theme CSS from external source\n# You can use https://github.com/georgekhananaev/fastapi-swagger-dark\ndark_theme_url = \"https://raw.githubusercontent.com/georgekhananaev/fastapi-swagger-dark/main/src/fastapi_swagger_dark/swagger_ui_dark.min.css\"\ncustom_css = requests.get(dark_theme_url).text\n\n# Custom JavaScript for analytics\ncustom_js = \"\"\"\nconsole.log('\ud83d\udcca Documentation accessed at:', new Date().toISOString());\ndocument.addEventListener('DOMContentLoaded', function() {\n    console.log('Dark theme loaded!');\n});\n\"\"\"\n\n# Apply with custom styling\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"},\n    custom_css=custom_css,\n    custom_js=custom_js\n)\n```\n\n#### Using with fastapi-swagger-dark\n\nFor a complete dark theme solution, you can use the [fastapi-swagger-dark](https://github.com/georgekhananaev/fastapi-swagger-dark) package:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_docshield import DocShield\nimport requests\n\napp = FastAPI()\n\n# Fetch dark theme CSS\nresponse = requests.get(\n    \"https://raw.githubusercontent.com/georgekhananaev/fastapi-swagger-dark/main/src/fastapi_swagger_dark/swagger_ui_dark.min.css\"\n)\ndark_css = response.text\n\nDocShield(\n    app=app,\n    credentials={\"admin\": \"password123\"},\n    custom_css=dark_css  # Apply dark theme\n)\n```\n\nSee [examples/custom_styling.py](examples/custom_styling.py) for more customization examples including:\n- \u2728 Minimal clean theme\n- \ud83c\udfe2 Corporate theme with analytics\n- \ud83d\udcd6 ReDoc customization\n- \ud83c\udfa8 Custom branding\n\n## Running Demo\n\n```bash\n# Run the demo app\npython demo.py\n\n# Visit http://localhost:8000/docs\n# Username: admin\n# Password: password123\n```\n\n## Running Tests\n\n```bash\n# Install test dependencies\npip install pytest httpx\n\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=fastapi_docshield\n```\n\n## Features\n\n- Protect Swagger UI, ReDoc, and OpenAPI JSON endpoints\n- Customizable endpoint URLs\n- Multiple username/password combinations\n- **Automatic CDN fallback** - Falls back to local files if CDN is unavailable\n- **Local file preference option** - Serve documentation from local files for better reliability\n- **Custom CSS and JavaScript injection** - Fully customize the look and behavior of documentation\n- **Resilient documentation** - Works even when CDN is down or blocked\n- Tested on Python 3.7-3.13\n- Compatible with uv package manager\n\n## Changelog\n\n### Version 0.2.1 (2025-08-17)\n- **Fixed**: Blank page issue after authentication for some users\n  - Improved handling of custom URL parameters by storing them as instance variables\n  - Simplified `_setup_routes()` method for better maintainability\n  - Applied fix from PR #2 for more robust URL parameter handling\n- **Fixed**: Route removal logic now correctly removes all default documentation routes\n  - Properly removes `/docs`, `/redoc`, and `/openapi.json` endpoints\n  - Prevents 500 errors when accessing old endpoints\n- **Improved**: Example files and documentation\n  - Fixed `custom_styling.py` to work with uvicorn by adding default app variable\n  - Standardized credentials across all custom styling examples\n  - Added `python-multipart` to dev dependencies for form data handling\n  - Added clear run instructions in example files\n\n### Version 0.2.0 (2025-08-17)\n- **Added**: Custom CSS and JavaScript injection support\n  - New `custom_css` parameter to inject custom styles into documentation pages\n  - New `custom_js` parameter to inject custom JavaScript for enhanced functionality\n  - Complete customization examples for dark theme, minimal theme, corporate branding, and analytics\n  - Support for both Swagger UI and ReDoc customization\n- **Added**: Automatic CDN fallback to local files for better reliability\n  - Documentation now automatically falls back to bundled static files if CDN is unavailable\n  - New `prefer_local` option to always serve from local files\n  - New `use_cdn_fallback` option to control fallback behavior\n  - Bundled Swagger UI and ReDoc static files for offline capability\n- **Fixed**: Static file URL bug that caused blank documentation pages\n  - Previously, when no custom CDN URLs were provided, the package would pass `None` values to FastAPI's documentation functions\n  - This resulted in HTML with `href=\"None\"` and `src=\"None\"`, causing white/blank pages\n  - Now properly handles default CDN URLs when custom URLs are not specified\n\n### Version 0.1.0 (2025-01-15)\n- Initial release\n- Basic HTTP authentication for FastAPI documentation endpoints\n- Support for multiple users\n\n## License\n\nMIT License - Copyright (c) 2025 George Khananaev",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 George Khananaev\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "A simple FastAPI integration to protect documentation endpoints with authentication",
    "version": "0.2.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/georgekhananaev/fastapi-docshield/issues",
        "Documentation": "https://github.com/georgekhananaev/fastapi-docshield#readme",
        "Homepage": "https://github.com/georgekhananaev/fastapi-docshield",
        "Source Code": "https://github.com/georgekhananaev/fastapi-docshield"
    },
    "split_keywords": [
        "authentication",
        " documentation",
        " fastapi",
        " security"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "a44273a8b9c91674183f5cf6ad3d7bfecc6b2f525bc03ec8e2519074d779b2d9",
                "md5": "13e3dc2e24d2507493314c504dce0efb",
                "sha256": "8558cf038c947e79fddbeac2b9207e3ad9204f42a879ed36d30a63d8428d1048"
            },
            "downloads": -1,
            "filename": "fastapi_docshield-0.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "13e3dc2e24d2507493314c504dce0efb",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 762900,
            "upload_time": "2025-08-17T11:39:34",
            "upload_time_iso_8601": "2025-08-17T11:39:34.726770Z",
            "url": "https://files.pythonhosted.org/packages/a4/42/73a8b9c91674183f5cf6ad3d7bfecc6b2f525bc03ec8e2519074d779b2d9/fastapi_docshield-0.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "186c8aeca2c9b9b6472c4d372a29ef5b337c890e6ff4af83e2c19eb530580493",
                "md5": "c466536fef750bce2f46327ec8cc1093",
                "sha256": "135a6ffe5a59784426f884de7860a64e31f63103ae99cab69863662800d21ca6"
            },
            "downloads": -1,
            "filename": "fastapi_docshield-0.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "c466536fef750bce2f46327ec8cc1093",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 758231,
            "upload_time": "2025-08-17T11:39:35",
            "upload_time_iso_8601": "2025-08-17T11:39:35.832123Z",
            "url": "https://files.pythonhosted.org/packages/18/6c/8aeca2c9b9b6472c4d372a29ef5b337c890e6ff4af83e2c19eb530580493/fastapi_docshield-0.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-17 11:39:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "georgekhananaev",
    "github_project": "fastapi-docshield",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-docshield"
}
        
Elapsed time: 0.73417s