| Name | fastmarkdocs JSON |
| Version |
0.4.2
JSON |
| download |
| home_page | None |
| Summary | A powerful library for enhancing FastAPI applications with rich markdown-based API documentation |
| upload_time | 2025-09-10 16:19:12 |
| maintainer | None |
| docs_url | None |
| author | Dan Vatca |
| requires_python | <4.0,>=3.9.2 |
| license | MIT |
| keywords |
fastapi
markdown
documentation
openapi
api
docs
|
| VCS |
 |
| bugtrack_url |
|
| requirements |
No requirements were recorded.
|
| Travis-CI |
No Travis.
|
| coveralls test coverage |
No coveralls.
|
# FastMarkDocs
A powerful library for enhancing FastAPI applications with rich markdown-based API documentation. Transform your API documentation workflow with beautiful, maintainable markdown files that generate comprehensive OpenAPI enhancements.
[](https://badge.fury.io/py/FastMarkDocs)
[](https://pypi.org/project/fastmarkdocs/)
[](https://opensource.org/licenses/MIT)
[](https://github.com/danvatca/fastmarkdocs/actions)
[](https://codecov.io/gh/danvatca/FastMarkDocs)
## Features
โจ **Rich Documentation**: Transform markdown files into comprehensive API documentation<br/>
๐ง **OpenAPI Enhancement**: Automatically enhance your OpenAPI/Swagger schemas<br/>
๐ท๏ธ **Smart Tag Descriptions**: Automatically extract tag descriptions from markdown Overview sections<br/>
๐ **Multi-language Code Samples**: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL<br/>
๐ **Markdown-First**: Write documentation in familiar markdown format<br/>
๐ **API Cross-References**: Include links to other APIs in your system with automatic formatting<br/>
๐จ **Customizable Templates**: Use custom templates for code generation<br/>
โก **High Performance**: Built-in caching and optimized processing<br/>
๐งช **Well Tested**: Comprehensive test suite with 100+ tests<br/>
๐ **Documentation Linting**: Built-in `fmd-lint` tool to analyze and improve documentation quality<br/>
๐๏ธ **Documentation Scaffolding**: `fmd-init` tool to bootstrap documentation for existing projects<br/>
## Quick Start
### Installation
#### Basic Installation
```bash
pip install fastmarkdocs
```
#### Development Installation
```bash
# Clone the repository
git clone https://github.com/danvatca/fastmarkdocs.git
cd fastmarkdocs
# Install with Poetry (recommended)
poetry install
# Or with pip in development mode
pip install -e ".[dev]"
```
#### Documentation Development
For building and contributing to documentation:
```bash
# Install Ruby and Jekyll dependencies:
# On macOS: brew install ruby && gem install bundler jekyll
# On Ubuntu: sudo apt-get install ruby-full build-essential zlib1g-dev
# Setup and serve documentation
./build-docs.sh setup
./build-docs.sh serve
```
### Basic Usage
```python
from fastapi import FastAPI
from fastmarkdocs import enhance_openapi_with_docs
app = FastAPI()
# Enhance your OpenAPI schema with markdown documentation
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com",
custom_headers={"Authorization": "Bearer token123"},
general_docs_file="general_docs.md" # Optional: specify general documentation
)
# Update your app's OpenAPI schema
app.openapi_schema = enhanced_schema
```
### Advanced Usage with API Links
For microservice architectures where you want to link between different APIs:
```python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastmarkdocs import APILink, enhance_openapi_with_docs
app = FastAPI()
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
# Define links to other APIs in your system
api_links = [
APILink(url="/docs", description="Authorization"),
APILink(url="/api/storage/docs", description="Storage"),
APILink(url="/api/monitoring/docs", description="Monitoring"),
]
openapi_schema = get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
)
# Enhance with custom title, description, and API links
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=openapi_schema,
docs_directory="docs/api",
app_title="My API Gateway",
app_description="Authorization and access control service",
api_links=api_links,
)
app.openapi_schema = enhanced_schema
return app.openapi_schema
app.openapi = custom_openapi
```
### Documentation Structure
Create markdown files in your docs directory:
```
docs/api/
โโโ users.md
โโโ authentication.md
โโโ orders.md
```
Example markdown file (`users.md`):
```markdown
# User Management API
## GET /users
Retrieve a list of all users in the system.
### Description
This endpoint returns a paginated list of users with their basic information.
### Parameters
- `page` (integer, optional): Page number for pagination (default: 1)
- `limit` (integer, optional): Number of users per page (default: 10)
### Response Examples
```json
{
"users": [
{
"id": 1,
"username": "john_doe",
"email": "john@example.com"
}
],
"total": 100,
"page": 1,
"limit": 10
}
```
### Code Samples
```python
import requests
response = requests.get("https://api.example.com/users")
users = response.json()
```
```javascript
const response = await fetch('https://api.example.com/users');
const users = await response.json();
```
```
## Smart Tag Descriptions
FastMarkDocs automatically extracts rich tag descriptions from markdown **Overview** sections, creating comprehensive OpenAPI tag documentation without manual configuration.
### How It Works
When you include an `## Overview` section in your markdown files, FastMarkDocs automatically:
1. **Extracts** the overview content (including subsections, formatting, and emojis)
2. **Associates** it with all tags used in that file
3. **Enhances** your OpenAPI schema with a proper `tags` section
### Example Structure
Create markdown files with Overview sections:
**`docs/api/users.md`:**
```markdown
# User Management API
## Overview
The **User Management API** provides comprehensive user account administration for enterprise applications, enabling centralized user lifecycle management with role-based access control and multi-factor authentication.
### ๐ฅ **User Management Features**
- User account creation with customizable roles and permissions
- Profile management and account status control (enable/disable)
- Secure user deletion with data integrity protection
### ๐ก๏ธ **Security Features**
- Configurable password complexity requirements
- Multi-factor authentication with TOTP support
- Comprehensive audit logging for compliance
## Endpoints
### GET /users
List all users in the system.
Tags: users, list
### POST /users
Create a new user account.
Tags: users, create
```
**`docs/api/authentication.md`:**
```markdown
# Authentication API
## Overview
The **Authentication API** handles secure user login, session management, and security token operations. This API provides robust authentication mechanisms including multi-factor authentication and secure session handling.
### ๐ **Authentication Features**
- JWT-based authentication with configurable expiration
- Multi-factor authentication with recovery codes
- Session management with automatic timeout
## Endpoints
### POST /auth/login
Authenticate a user and create a session.
Tags: authentication, login
### POST /auth/logout
Logout a user and invalidate the session.
Tags: authentication, logout
```
### Generated OpenAPI Enhancement
FastMarkDocs automatically creates this in your OpenAPI schema:
```json
{
"tags": [
{
"name": "users",
"description": "The **User Management API** provides comprehensive user account administration for enterprise applications, enabling centralized user lifecycle management with role-based access control and multi-factor authentication.\n\n### ๐ฅ **User Management Features**\n\n- User account creation with customizable roles and permissions\n- Profile management and account status control (enable/disable)\n- Secure user deletion with data integrity protection\n\n### ๐ก๏ธ **Security Features**\n\n- Configurable password complexity requirements\n- Multi-factor authentication with TOTP support\n- Comprehensive audit logging for compliance"
},
{
"name": "authentication",
"description": "The **Authentication API** handles secure user login, session management, and security token operations. This API provides robust authentication mechanisms including multi-factor authentication and secure session handling.\n\n### ๐ **Authentication Features**\n\n- JWT-based authentication with configurable expiration\n- Multi-factor authentication with recovery codes\n- Session management with automatic timeout"
}
]
}
```
### Benefits
- ๐ **No Extra Configuration**: Works automatically with existing markdown files
- ๐จ **Rich Formatting**: Preserves markdown formatting, emojis, and structure
- ๐ **Consistent Documentation**: Same overview content appears in both markdown and OpenAPI docs
- ๐ท๏ธ **Smart Association**: All tags in a file share the same overview description
- ๐ง **Backward Compatible**: Doesn't affect existing functionality
## CLI Tools
FastMarkDocs includes powerful CLI tools for creating and analyzing your API documentation.
### Documentation Initialization with fmd-init
The `fmd-init` tool helps you bootstrap documentation for existing FastAPI projects by scanning your code and generating markdown scaffolding:
```bash
# Basic usage - scan src/ directory
fmd-init src/
# Custom output directory
fmd-init src/ --output-dir api-docs/
# Preview what would be generated (dry run)
fmd-init src/ --dry-run --verbose
# JSON output format
fmd-init src/ --format json
# Overwrite existing files
fmd-init src/ --overwrite
# Skip generating .fmd-lint.yaml configuration file
fmd-init src/ --no-config
```
**Features:**
- ๐ **Automatic Discovery**: Scans Python files for FastAPI decorators (`@app.get`, `@router.post`, etc.)
- ๐ **Markdown Generation**: Creates structured documentation files grouped by tags
- ๐๏ธ **Scaffolding**: Generates TODO sections for parameters, responses, and examples
- ๐ **Linter Configuration**: Automatically generates `.fmd-lint.yaml` config file tailored to your project
- ๐ง **Flexible Output**: Supports text and JSON formats, dry-run mode, custom directories
- ๐ **Detailed Reporting**: Shows endpoint breakdown by HTTP method and file locations
**Example Output:**
```
โ
Documentation scaffolding generated successfully!
๐ **Documentation Initialization Complete**
- **Endpoints discovered:** 15
- **Files generated:** 4
**Endpoints by method:**
- DELETE: 2
- GET: 8
- POST: 3
- PUT: 2
**Generated files:**
- docs/users.md
- docs/orders.md
- docs/admin.md
- docs/root.md
- .fmd-lint.yaml (linter configuration)
```
**Workflow Integration:**
1. ๐๏ธ Develop FastAPI endpoints in your project
2. ๐ Run `fmd-init src/` to generate documentation scaffolding and linter config
3. โ๏ธ Review and enhance the generated documentation
4. ๐ง Use fastmarkdocs to enhance your OpenAPI schema
5. ๐งช Run `fmd-lint` to check documentation quality (uses generated config)
6. ๐ Deploy with enhanced documentation!
**Automatic Linter Configuration:**
`fmd-init` automatically generates a `.fmd-lint.yaml` configuration file tailored to your project:
- **Smart Exclusions**: Detects common patterns (health checks, metrics, static files, admin endpoints) and suggests appropriate exclusions
- **Project-Specific Paths**: Configures documentation and OpenAPI paths based on your setup
- **Ready to Use**: The generated config works immediately with `fmd-lint`
- **Customizable**: Easily modify the generated config to match your specific needs
Example generated configuration:
```yaml
# FastMarkDocs Linter Configuration
# Generated automatically by fmd-init
exclude:
endpoints:
- path: "^/(health|ready|live|ping)"
methods: [".*"]
- path: "^/metrics"
methods: ["GET"]
openapi: "./openapi.json"
docs:
- "./docs"
recursive: true
base_url: "https://api.example.com"
```
### Documentation Linting with fmd-lint
FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:
```bash
# Install FastMarkDocs (includes fmd-lint)
pip install fastmarkdocs
# Lint your documentation
fmd-lint --openapi openapi.json --docs docs/api
# Use configuration file for advanced settings
fmd-lint --config .fmd-lint.yaml
```
**Configuration File Support:**
Create a `.fmd-lint.yaml` file to streamline your workflow:
```yaml
exclude:
endpoints:
- path: "^/static/.*"
methods: ["GET"]
- path: "^/health"
methods: [".*"]
spec_generator:
- "poetry run python ./generate_openapi.py"
docs:
- "./docs/api"
recursive: true
base_url: "https://api.example.com"
```
### What fmd-lint Analyzes
- **Missing Documentation**: Finds API endpoints without documentation
- **Incomplete Documentation**: Identifies missing descriptions, examples, or code samples
- **Common Mistakes**: Detects path parameter mismatches and other errors
- **Orphaned Documentation**: Finds docs for non-existent endpoints
- **Enhancement Failures**: Tests that documentation properly enhances OpenAPI
### Example Output
```
============================================================
๐ FastMarkDocs Documentation Linter Results
============================================================
๐ โ
Good documentation with 3 minor issues to address.
๐ Coverage: 85.7% | Completeness: 72.3% | Issues: 3
โ Missing Documentation:
โข GET /users/{id}
โข POST /orders
โ ๏ธ Common Mistakes:
โข path_parameter_mismatch: GET /users/{id} should be /users/{user_id}
๐ก Check if path parameters match your FastAPI routes
๐ก Recommendations:
โ ๏ธ Fix Documentation Mistakes
Action: Review and fix path parameter mismatches
```
### CI/CD Integration
```yaml
# GitHub Actions example
- name: Lint documentation
run: fmd-lint --openapi openapi.json --docs docs/api
```
For complete documentation, see [docs/fmd-lint.md](docs/fmd-lint.md). For configuration file details, see [docs/configuration.md](docs/configuration.md).
## Advanced Features
### General Documentation
FastMarkDocs supports "general documentation" that provides global information about your API. This content is included in the OpenAPI schema's `info.description` field and appears at the top of your API documentation.
#### How General Docs Work
1. **Default File**: Create a `general_docs.md` file in your docs directory
2. **Custom File**: Specify a different file using the `general_docs_file` parameter
3. **Global Content**: The content appears in the API overview, not in individual endpoints
#### Example General Documentation
Create a file `docs/api/general_docs.md`:
```markdown
# API Overview
Welcome to our comprehensive API documentation. This API provides access to user management, order processing, and analytics features.
## Authentication
All API endpoints require authentication using Bearer tokens:
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/users
```
## Rate Limiting
API requests are limited to 1000 requests per hour per API key.
## Error Handling
Our API uses standard HTTP status codes and returns JSON error responses:
```json
{
"error": "invalid_request",
"message": "The request is missing required parameters"
}
```
## Support
For API support, contact: api-support@example.com
```
#### Using General Documentation
```python
from fastmarkdocs import enhance_openapi_with_docs
# Default: Uses general_docs.md if it exists
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api"
)
# Custom general docs file
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
general_docs_file="api_overview.md"
)
# Disable general docs by passing None
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
general_docs_file=None
)
```
#### General Docs with MarkdownDocumentationLoader
```python
from fastmarkdocs import MarkdownDocumentationLoader
# Load with custom general docs
loader = MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs = loader.load_documentation()
# Access general docs content (internal use)
if hasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_content is not None)
```
### Authentication Schemes
FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:
```python
from fastmarkdocs import enhance_openapi_with_docs, CodeSampleGenerator
# Configure automatic authentication headers
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com",
# Automatically adds appropriate auth headers to all code samples
authentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directly
generator = CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemes
custom_headers={"User-Agent": "MyApp/1.0"}
)
```
**Supported Authentication Schemes:**
- `"bearer"` - Adds `Authorization: Bearer YOUR_TOKEN_HERE` header
- `"api_key"` - Adds `X-API-Key: YOUR_API_KEY_HERE` header
- `"basic"` - Adds `Authorization: Basic YOUR_CREDENTIALS_HERE` header
### Server URLs and Multi-Environment Support
Configure multiple server URLs for different environments:
```python
from fastmarkdocs import enhance_openapi_with_docs
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary server
server_urls=[ # Additional servers for code samples
"https://api.example.com",
"https://staging-api.example.com",
"https://dev-api.example.com"
]
)
```
### Custom Code Generation
```python
from fastmarkdocs import CodeSampleGenerator
from fastmarkdocs.types import CodeLanguage
generator = CodeSampleGenerator(
base_url="https://api.example.com",
code_sample_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],
custom_headers={"Authorization": "Bearer token"},
authentication_schemes=["bearer"], # Automatic auth headers
server_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True # Enable caching for better performance
)
# Generate samples for a specific endpoint
samples = generator.generate_samples_for_endpoint(endpoint_data)
```
### Custom Code Templates
Create custom templates for specific languages with dynamic variables:
```python
from fastmarkdocs import CodeSampleGenerator
from fastmarkdocs.types import CodeLanguage
# Define custom templates with variables
custom_templates = {
CodeLanguage.PYTHON: """
# {summary}
# {description}
import requests
def call_{method_lower}_api():
response = requests.{method_lower}(
'{url}',
headers={{'Authorization': 'Bearer YOUR_TOKEN'}}
)
return response.json()
# Usage
result = call_{method_lower}_api()
print(result)
""",
CodeLanguage.BASH: """
#!/bin/bash
# {summary}
curl -X {method} \\
'{url}' \\
-H 'Authorization: Bearer YOUR_TOKEN' \\
-H 'Content-Type: application/json'
"""
}
generator = CodeSampleGenerator(
base_url="https://api.example.com",
custom_templates=custom_templates
)
```
**Available Template Variables:**
- `{method}` - HTTP method (GET, POST, etc.)
- `{method_lower}` - HTTP method in lowercase
- `{path}` - API endpoint path
- `{url}` - Complete URL
- `{base_url}` - Base URL
- `{summary}` - Endpoint summary
- `{description}` - Endpoint description
### Advanced Loader Configuration
```python
from fastmarkdocs import MarkdownDocumentationLoader
from fastmarkdocs.types import CodeLanguage
loader = MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samples
file_patterns=["*.md", "*.markdown"], # File types to process
encoding="utf-8",
recursive=True, # Search subdirectories
cache_enabled=True, # Enable caching for performance
cache_ttl=3600, # Cache for 1 hour
general_docs_file="api_overview.md" # Custom general docs file
)
```
## API Reference
### Core Functions
#### `enhance_openapi_with_docs()`
Enhance an OpenAPI schema with markdown documentation.
**Parameters:**
- `openapi_schema` (dict): The original OpenAPI schema
- `docs_directory` (str): Path to markdown documentation directory
- `base_url` (str, optional): Base URL for code samples (default: "https://api.example.com")
- `include_code_samples` (bool, optional): Whether to include code samples (default: True)
- `include_response_examples` (bool, optional): Whether to include response examples (default: True)
- `code_sample_languages` (list[CodeLanguage], optional): Languages for code generation
- `custom_headers` (dict, optional): Custom headers for code samples
- `app_title` (str, optional): Override the application title
- `app_description` (str, optional): Application description to include
- `api_links` (list[APILink], optional): List of links to other APIs
- `general_docs_file` (str, optional): Path to general documentation file (default: "general_docs.md" if found)
**Returns:** Enhanced OpenAPI schema (dict)
**Basic Example:**
```python
from fastmarkdocs import enhance_openapi_with_docs
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com",
include_code_samples=True,
include_response_examples=True,
general_docs_file="general_docs.md" # Optional: specify general documentation
)
```
**Example with API Links:**
```python
from fastmarkdocs import APILink, enhance_openapi_with_docs
# Define links to other APIs in your system
api_links = [
APILink(url="/docs", description="Authorization"),
APILink(url="/api/storage/docs", description="Storage"),
APILink(url="/api/monitoring/docs", description="Monitoring"),
]
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
app_title="My API Gateway",
app_description="Authorization and access control service",
api_links=api_links,
general_docs_file="general_docs.md" # Optional: include general documentation
)
```
**Example with General Documentation:**
```python
# Using default general_docs.md file
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api"
# Automatically includes content from docs/api/general_docs.md
)
# Using custom general documentation file
enhanced_schema = enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
```
### Configuration Classes
#### `MarkdownDocumentationConfig`
Configuration for markdown documentation loading.
```python
from fastmarkdocs import MarkdownDocumentationConfig, CodeLanguage
config = MarkdownDocumentationConfig(
docs_directory="docs/api",
base_url_placeholder="https://api.example.com",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],
file_patterns=["*.md", "*.markdown"],
encoding="utf-8",
recursive=True,
cache_enabled=True,
cache_ttl=3600 # 1 hour
)
```
#### `OpenAPIEnhancementConfig`
Configuration for OpenAPI schema enhancement.
```python
from fastmarkdocs import OpenAPIEnhancementConfig, CodeLanguage
config = OpenAPIEnhancementConfig(
include_code_samples=True,
include_response_examples=True,
include_parameter_examples=True,
code_sample_languages=[CodeLanguage.CURL, CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT],
base_url="https://api.example.com",
server_urls=["https://api.example.com", "https://staging-api.example.com"],
custom_headers={"Authorization": "Bearer {token}"},
authentication_schemes=["bearerAuth", "apiKey"]
)
```
### Types and Data Classes
#### `APILink`
Represents a link to another API in your system.
```python
from fastmarkdocs import APILink
# Create API links
api_link = APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docs
api_links = [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]
```
#### `DocumentationData`
Container for all documentation data loaded from markdown files.
```python
from fastmarkdocs import DocumentationData, EndpointDocumentation
data = DocumentationData(
endpoints=[], # List of EndpointDocumentation
global_examples=[], # List of CodeSample
metadata={} # Dict of metadata
)
# Access endpoints
for endpoint in data.endpoints:
print(f"{endpoint.method} {endpoint.path}")
```
#### `EndpointDocumentation`
Documentation for a single API endpoint.
```python
from fastmarkdocs import EndpointDocumentation, HTTPMethod, CodeSample
endpoint = EndpointDocumentation(
path="/users/{user_id}",
method=HTTPMethod.GET,
summary="Get user by ID",
description="Retrieve a specific user by their unique identifier",
code_samples=[], # List of CodeSample
response_examples=[], # List of ResponseExample
parameters=[], # List of ParameterDocumentation
tags=["users"],
deprecated=False
)
```
#### `CodeSample`
Represents a code sample in a specific language.
```python
from fastmarkdocs import CodeSample, CodeLanguage
sample = CodeSample(
language=CodeLanguage.PYTHON,
code="""
import requests
response = requests.get("https://api.example.com/users/123")
user = response.json()
""",
description="Get user by ID using requests library",
title="Python Example"
)
```
### Core Classes
#### `MarkdownDocumentationLoader`
Load and process markdown documentation files from a directory.
**Parameters:**
- `docs_directory` (str): Path to markdown documentation directory (default: "docs")
- `base_url_placeholder` (str): Placeholder URL for code samples (default: "https://api.example.com")
- `supported_languages` (list[CodeLanguage], optional): Languages to support for code samples
- `file_patterns` (list[str], optional): File patterns to match (default: ["*.md", "*.markdown"])
- `encoding` (str): File encoding (default: "utf-8")
- `recursive` (bool): Whether to search directories recursively (default: True)
- `cache_enabled` (bool): Whether to enable caching (default: True)
- `cache_ttl` (int): Cache time-to-live in seconds (default: 3600)
- `general_docs_file` (str, optional): Path to general documentation file
**Methods:**
- `load_documentation()` โ `DocumentationData`: Load all documentation
- `parse_markdown_file(file_path)` โ `dict`: Parse a single markdown file
- `clear_cache()`: Clear the documentation cache
- `get_stats()` โ `dict`: Get loading statistics
```python
from fastmarkdocs import MarkdownDocumentationLoader, CodeLanguage
loader = MarkdownDocumentationLoader(
docs_directory="docs/api",
recursive=True,
cache_enabled=True,
cache_ttl=3600,
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],
general_docs_file="overview.md"
)
# Load all documentation
docs = loader.load_documentation()
# Get statistics
stats = loader.get_stats()
print(f"Loaded {stats['total_endpoints']} endpoints")
```
#### `CodeSampleGenerator`
Generate code samples for API endpoints in multiple languages.
**Parameters:**
- `base_url` (str): Base URL for code samples (default: "https://api.example.com")
- `custom_headers` (dict[str, str]): Custom headers to include
- `code_sample_languages` (list[CodeLanguage]): Languages to generate
- `custom_templates` (dict[CodeLanguage, str]): Custom code templates
**Methods:**
- `generate_samples_for_endpoint(endpoint_data)` โ `list[CodeSample]`: Generate samples for an endpoint
- `generate_curl_sample(method, url, headers, body)` โ `CodeSample`: Generate cURL sample
- `generate_python_sample(method, url, headers, body)` โ `CodeSample`: Generate Python sample
```python
from fastmarkdocs import CodeSampleGenerator, CodeLanguage
generator = CodeSampleGenerator(
base_url="https://api.example.com",
custom_headers={"Authorization": "Bearer {token}", "Content-Type": "application/json"},
code_sample_languages=[CodeLanguage.CURL, CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT],
custom_templates={
CodeLanguage.PYTHON: """
import requests
def {method_lower}_{path_safe}():
headers = {headers}
response = requests.{method_lower}("{url}", headers=headers)
return response.json()
"""
}
)
# Generate samples for an endpoint
samples = generator.generate_samples_for_endpoint({
"method": "GET",
"path": "/users/{user_id}",
"parameters": {"user_id": 123}
})
```
#### `OpenAPIEnhancer`
Enhance OpenAPI schemas with documentation data and code samples.
**Parameters:**
- `base_url` (str): Base URL for code samples
- `custom_headers` (dict[str, str]): Custom headers for code samples
- `code_sample_languages` (list[CodeLanguage]): Languages for code generation
- `include_code_samples` (bool): Whether to include code samples (default: True)
- `include_response_examples` (bool): Whether to include response examples (default: True)
**Methods:**
- `enhance_openapi_schema(schema, documentation_data)` โ `dict`: Enhance a schema
- `add_code_samples_to_operation(operation, endpoint)`: Add code samples to an operation
- `add_response_examples_to_operation(operation, endpoint)`: Add response examples
```python
from fastmarkdocs import OpenAPIEnhancer, CodeLanguage
enhancer = OpenAPIEnhancer(
base_url="https://api.example.com",
custom_headers={"X-API-Key": "your-key"},
code_sample_languages=[CodeLanguage.PYTHON, CodeLanguage.GO],
include_code_samples=True,
include_response_examples=True
)
# Enhance schema
enhanced = enhancer.enhance_openapi_schema(openapi_schema, documentation_data)
```
## Supported Languages
The library supports code generation for:
- **Python** - Using `requests` library
- **JavaScript** - Using `fetch` API
- **TypeScript** - With proper type annotations
- **Go** - Using `net/http` package
- **Java** - Using `HttpURLConnection`
- **PHP** - Using `cURL`
- **Ruby** - Using `net/http`
- **C#** - Using `HttpClient`
- **cURL** - Command-line examples
## Error Handling
The library provides comprehensive error handling:
```python
from fastmarkdocs.exceptions import (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs = loader.load_documentation()
except DocumentationLoadError as e:
print(f"Failed to load documentation: {e}")
```
## Testing
Run the test suite:
```bash
# Install development dependencies
pip install -e ".[dev]"
# Run all tests
pytest
# Run with coverage
pytest --cov=fastmarkdocs
# Run specific test categories
pytest -m unit
pytest -m integration
```
## Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for your changes
5. Run the test suite (`pytest`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request
## Documentation Development
To build and test the documentation locally:
```bash
# First time setup (install Ruby dependencies)
./build-docs.sh setup
# Build and serve locally with live reload
./build-docs.sh serve
# Or using Make
make -f Makefile.docs docs-serve
```
The documentation will be available at `http://localhost:4001` with automatic reloading when you make changes.
See [src/docs/BUILD.md](src/docs/BUILD.md) for detailed documentation build instructions.
## Development Setup
```bash
# Clone the repository
git clone https://github.com/yourusername/fastmarkdocs.git
cd fastmarkdocs
# Install Poetry (if not already installed)
curl -sSL https://install.python-poetry.org | python3 -
# Install dependencies
poetry install
# Activate virtual environment
poetry shell
# Run tests
pytest
```
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes.
## Support
- ๐ [Documentation](https://github.com/danvatca/fastmarkdocs)
- ๐ [Issue Tracker](https://github.com/danvatca/fastmarkdocs/issues)
- ๐ฌ [Discussions](https://github.com/danvatca/fastmarkdocs/discussions)
## Related Projects
- [FastAPI](https://fastapi.tiangolo.com/) - The web framework this library enhances
- [OpenAPI](https://swagger.io/specification/) - The specification this library extends
- [Swagger UI](https://swagger.io/tools/swagger-ui/) - The UI that displays the enhanced documentation
Raw data
{
"_id": null,
"home_page": null,
"name": "fastmarkdocs",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.9.2",
"maintainer_email": null,
"keywords": "fastapi, markdown, documentation, openapi, api, docs",
"author": "Dan Vatca",
"author_email": "dan.vatca@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/89/6a/84f039e4ff5f6a1329749b0023b4aa6012be200e0bca9e01e9c6cc3dcf81/fastmarkdocs-0.4.2.tar.gz",
"platform": null,
"description": "# FastMarkDocs\n\nA powerful library for enhancing FastAPI applications with rich markdown-based API documentation. Transform your API documentation workflow with beautiful, maintainable markdown files that generate comprehensive OpenAPI enhancements.\n\n[](https://badge.fury.io/py/FastMarkDocs)\n[](https://pypi.org/project/fastmarkdocs/)\n[](https://opensource.org/licenses/MIT)\n[](https://github.com/danvatca/fastmarkdocs/actions)\n[](https://codecov.io/gh/danvatca/FastMarkDocs)\n\n## Features\n\n\u2728 **Rich Documentation**: Transform markdown files into comprehensive API documentation<br/>\n\ud83d\udd27 **OpenAPI Enhancement**: Automatically enhance your OpenAPI/Swagger schemas<br/>\n\ud83c\udff7\ufe0f **Smart Tag Descriptions**: Automatically extract tag descriptions from markdown Overview sections<br/>\n\ud83c\udf0d **Multi-language Code Samples**: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL<br/>\n\ud83d\udcdd **Markdown-First**: Write documentation in familiar markdown format<br/>\n\ud83d\udd17 **API Cross-References**: Include links to other APIs in your system with automatic formatting<br/>\n\ud83c\udfa8 **Customizable Templates**: Use custom templates for code generation<br/>\n\u26a1 **High Performance**: Built-in caching and optimized processing<br/>\n\ud83e\uddea **Well Tested**: Comprehensive test suite with 100+ tests<br/>\n\ud83d\udd0d **Documentation Linting**: Built-in `fmd-lint` tool to analyze and improve documentation quality<br/>\n\ud83c\udfd7\ufe0f **Documentation Scaffolding**: `fmd-init` tool to bootstrap documentation for existing projects<br/>\n\n## Quick Start\n\n### Installation\n\n#### Basic Installation\n```bash\npip install fastmarkdocs\n```\n\n#### Development Installation\n```bash\n# Clone the repository\ngit clone https://github.com/danvatca/fastmarkdocs.git\ncd fastmarkdocs\n\n# Install with Poetry (recommended)\npoetry install\n\n# Or with pip in development mode\npip install -e \".[dev]\"\n```\n\n#### Documentation Development\nFor building and contributing to documentation:\n\n```bash\n# Install Ruby and Jekyll dependencies:\n# On macOS: brew install ruby && gem install bundler jekyll\n# On Ubuntu: sudo apt-get install ruby-full build-essential zlib1g-dev\n\n# Setup and serve documentation\n./build-docs.sh setup\n./build-docs.sh serve\n```\n\n### Basic Usage\n\n```python\nfrom fastapi import FastAPI\nfrom fastmarkdocs import enhance_openapi_with_docs\n\napp = FastAPI()\n\n# Enhance your OpenAPI schema with markdown documentation\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n base_url=\"https://api.example.com\",\n custom_headers={\"Authorization\": \"Bearer token123\"},\n general_docs_file=\"general_docs.md\" # Optional: specify general documentation\n)\n\n# Update your app's OpenAPI schema\napp.openapi_schema = enhanced_schema\n```\n\n### Advanced Usage with API Links\n\nFor microservice architectures where you want to link between different APIs:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.openapi.utils import get_openapi\nfrom fastmarkdocs import APILink, enhance_openapi_with_docs\n\napp = FastAPI()\n\ndef custom_openapi():\n if app.openapi_schema:\n return app.openapi_schema\n \n # Define links to other APIs in your system\n api_links = [\n APILink(url=\"/docs\", description=\"Authorization\"),\n APILink(url=\"/api/storage/docs\", description=\"Storage\"),\n APILink(url=\"/api/monitoring/docs\", description=\"Monitoring\"),\n ]\n \n openapi_schema = get_openapi(\n title=app.title,\n version=app.version,\n description=app.description,\n routes=app.routes,\n )\n \n # Enhance with custom title, description, and API links\n enhanced_schema = enhance_openapi_with_docs(\n openapi_schema=openapi_schema,\n docs_directory=\"docs/api\",\n app_title=\"My API Gateway\",\n app_description=\"Authorization and access control service\",\n api_links=api_links,\n )\n \n app.openapi_schema = enhanced_schema\n return app.openapi_schema\n\napp.openapi = custom_openapi\n```\n\n### Documentation Structure\n\nCreate markdown files in your docs directory:\n\n```\ndocs/api/\n\u251c\u2500\u2500 users.md\n\u251c\u2500\u2500 authentication.md\n\u2514\u2500\u2500 orders.md\n```\n\nExample markdown file (`users.md`):\n\n```markdown\n# User Management API\n\n## GET /users\n\nRetrieve a list of all users in the system.\n\n### Description\nThis endpoint returns a paginated list of users with their basic information.\n\n### Parameters\n- `page` (integer, optional): Page number for pagination (default: 1)\n- `limit` (integer, optional): Number of users per page (default: 10)\n\n### Response Examples\n\n```json\n{\n \"users\": [\n {\n \"id\": 1,\n \"username\": \"john_doe\",\n \"email\": \"john@example.com\"\n }\n ],\n \"total\": 100,\n \"page\": 1,\n \"limit\": 10\n}\n```\n\n### Code Samples\n\n```python\nimport requests\n\nresponse = requests.get(\"https://api.example.com/users\")\nusers = response.json()\n```\n\n```javascript\nconst response = await fetch('https://api.example.com/users');\nconst users = await response.json();\n```\n\n```\n\n## Smart Tag Descriptions\n\nFastMarkDocs automatically extracts rich tag descriptions from markdown **Overview** sections, creating comprehensive OpenAPI tag documentation without manual configuration.\n\n### How It Works\n\nWhen you include an `## Overview` section in your markdown files, FastMarkDocs automatically:\n1. **Extracts** the overview content (including subsections, formatting, and emojis)\n2. **Associates** it with all tags used in that file\n3. **Enhances** your OpenAPI schema with a proper `tags` section\n\n### Example Structure\n\nCreate markdown files with Overview sections:\n\n**`docs/api/users.md`:**\n```markdown\n# User Management API\n\n## Overview\n\nThe **User Management API** provides comprehensive user account administration for enterprise applications, enabling centralized user lifecycle management with role-based access control and multi-factor authentication.\n\n### \ud83d\udc65 **User Management Features**\n\n- User account creation with customizable roles and permissions\n- Profile management and account status control (enable/disable)\n- Secure user deletion with data integrity protection\n\n### \ud83d\udee1\ufe0f **Security Features**\n\n- Configurable password complexity requirements\n- Multi-factor authentication with TOTP support\n- Comprehensive audit logging for compliance\n\n## Endpoints\n\n### GET /users\nList all users in the system.\n\nTags: users, list\n\n### POST /users\nCreate a new user account.\n\nTags: users, create\n```\n\n**`docs/api/authentication.md`:**\n```markdown\n# Authentication API\n\n## Overview\n\nThe **Authentication API** handles secure user login, session management, and security token operations. This API provides robust authentication mechanisms including multi-factor authentication and secure session handling.\n\n### \ud83d\udd10 **Authentication Features**\n\n- JWT-based authentication with configurable expiration\n- Multi-factor authentication with recovery codes\n- Session management with automatic timeout\n\n## Endpoints\n\n### POST /auth/login\nAuthenticate a user and create a session.\n\nTags: authentication, login\n\n### POST /auth/logout\nLogout a user and invalidate the session.\n\nTags: authentication, logout\n```\n\n### Generated OpenAPI Enhancement\n\nFastMarkDocs automatically creates this in your OpenAPI schema:\n\n```json\n{\n \"tags\": [\n {\n \"name\": \"users\",\n \"description\": \"The **User Management API** provides comprehensive user account administration for enterprise applications, enabling centralized user lifecycle management with role-based access control and multi-factor authentication.\\n\\n### \ud83d\udc65 **User Management Features**\\n\\n- User account creation with customizable roles and permissions\\n- Profile management and account status control (enable/disable)\\n- Secure user deletion with data integrity protection\\n\\n### \ud83d\udee1\ufe0f **Security Features**\\n\\n- Configurable password complexity requirements\\n- Multi-factor authentication with TOTP support\\n- Comprehensive audit logging for compliance\"\n },\n {\n \"name\": \"authentication\", \n \"description\": \"The **Authentication API** handles secure user login, session management, and security token operations. This API provides robust authentication mechanisms including multi-factor authentication and secure session handling.\\n\\n### \ud83d\udd10 **Authentication Features**\\n\\n- JWT-based authentication with configurable expiration\\n- Multi-factor authentication with recovery codes\\n- Session management with automatic timeout\"\n }\n ]\n}\n```\n\n### Benefits\n\n- \ud83d\udcdd **No Extra Configuration**: Works automatically with existing markdown files\n- \ud83c\udfa8 **Rich Formatting**: Preserves markdown formatting, emojis, and structure\n- \ud83d\udd04 **Consistent Documentation**: Same overview content appears in both markdown and OpenAPI docs\n- \ud83c\udff7\ufe0f **Smart Association**: All tags in a file share the same overview description\n- \ud83d\udd27 **Backward Compatible**: Doesn't affect existing functionality\n\n## CLI Tools\n\nFastMarkDocs includes powerful CLI tools for creating and analyzing your API documentation.\n\n### Documentation Initialization with fmd-init\n\nThe `fmd-init` tool helps you bootstrap documentation for existing FastAPI projects by scanning your code and generating markdown scaffolding:\n\n```bash\n# Basic usage - scan src/ directory\nfmd-init src/\n\n# Custom output directory\nfmd-init src/ --output-dir api-docs/\n\n# Preview what would be generated (dry run)\nfmd-init src/ --dry-run --verbose\n\n# JSON output format\nfmd-init src/ --format json\n\n# Overwrite existing files\nfmd-init src/ --overwrite\n\n# Skip generating .fmd-lint.yaml configuration file\nfmd-init src/ --no-config\n```\n\n**Features:**\n- \ud83d\udd0d **Automatic Discovery**: Scans Python files for FastAPI decorators (`@app.get`, `@router.post`, etc.)\n- \ud83d\udcdd **Markdown Generation**: Creates structured documentation files grouped by tags\n- \ud83c\udfd7\ufe0f **Scaffolding**: Generates TODO sections for parameters, responses, and examples\n- \ud83d\udccb **Linter Configuration**: Automatically generates `.fmd-lint.yaml` config file tailored to your project\n- \ud83d\udd27 **Flexible Output**: Supports text and JSON formats, dry-run mode, custom directories\n- \ud83d\udcca **Detailed Reporting**: Shows endpoint breakdown by HTTP method and file locations\n\n**Example Output:**\n```\n\u2705 Documentation scaffolding generated successfully!\n\n\ud83d\udcca **Documentation Initialization Complete**\n- **Endpoints discovered:** 15\n- **Files generated:** 4\n\n**Endpoints by method:**\n- DELETE: 2\n- GET: 8\n- POST: 3\n- PUT: 2\n\n**Generated files:**\n- docs/users.md\n- docs/orders.md\n- docs/admin.md\n- docs/root.md\n- .fmd-lint.yaml (linter configuration)\n```\n\n**Workflow Integration:**\n1. \ud83c\udfd7\ufe0f Develop FastAPI endpoints in your project\n2. \ud83d\udd0d Run `fmd-init src/` to generate documentation scaffolding and linter config\n3. \u270f\ufe0f Review and enhance the generated documentation\n4. \ud83d\udd27 Use fastmarkdocs to enhance your OpenAPI schema\n5. \ud83e\uddea Run `fmd-lint` to check documentation quality (uses generated config)\n6. \ud83d\ude80 Deploy with enhanced documentation!\n\n**Automatic Linter Configuration:**\n\n`fmd-init` automatically generates a `.fmd-lint.yaml` configuration file tailored to your project:\n\n- **Smart Exclusions**: Detects common patterns (health checks, metrics, static files, admin endpoints) and suggests appropriate exclusions\n- **Project-Specific Paths**: Configures documentation and OpenAPI paths based on your setup\n- **Ready to Use**: The generated config works immediately with `fmd-lint`\n- **Customizable**: Easily modify the generated config to match your specific needs\n\nExample generated configuration:\n```yaml\n# FastMarkDocs Linter Configuration\n# Generated automatically by fmd-init\n\nexclude:\n endpoints:\n - path: \"^/(health|ready|live|ping)\"\n methods: [\".*\"]\n - path: \"^/metrics\"\n methods: [\"GET\"]\n\nopenapi: \"./openapi.json\"\ndocs:\n - \"./docs\"\nrecursive: true\nbase_url: \"https://api.example.com\"\n```\n\n### Documentation Linting with fmd-lint\n\nFastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:\n\n```bash\n# Install FastMarkDocs (includes fmd-lint)\npip install fastmarkdocs\n\n# Lint your documentation\nfmd-lint --openapi openapi.json --docs docs/api\n\n# Use configuration file for advanced settings\nfmd-lint --config .fmd-lint.yaml\n```\n\n**Configuration File Support:**\nCreate a `.fmd-lint.yaml` file to streamline your workflow:\n\n```yaml\nexclude:\n endpoints:\n - path: \"^/static/.*\"\n methods: [\"GET\"]\n - path: \"^/health\"\n methods: [\".*\"]\n\nspec_generator:\n - \"poetry run python ./generate_openapi.py\"\n\ndocs:\n - \"./docs/api\"\n\nrecursive: true\nbase_url: \"https://api.example.com\"\n```\n\n### What fmd-lint Analyzes\n\n- **Missing Documentation**: Finds API endpoints without documentation\n- **Incomplete Documentation**: Identifies missing descriptions, examples, or code samples\n- **Common Mistakes**: Detects path parameter mismatches and other errors\n- **Orphaned Documentation**: Finds docs for non-existent endpoints\n- **Enhancement Failures**: Tests that documentation properly enhances OpenAPI\n\n### Example Output\n\n```\n============================================================\n\ud83d\udd0d FastMarkDocs Documentation Linter Results\n============================================================\n\n\ud83d\udcca \u2705 Good documentation with 3 minor issues to address.\n\ud83d\udcc8 Coverage: 85.7% | Completeness: 72.3% | Issues: 3\n\n\u274c Missing Documentation:\n \u2022 GET /users/{id}\n \u2022 POST /orders\n\n\u26a0\ufe0f Common Mistakes:\n \u2022 path_parameter_mismatch: GET /users/{id} should be /users/{user_id}\n \ud83d\udca1 Check if path parameters match your FastAPI routes\n\n\ud83d\udca1 Recommendations:\n \u26a0\ufe0f Fix Documentation Mistakes\n Action: Review and fix path parameter mismatches\n```\n\n### CI/CD Integration\n\n```yaml\n# GitHub Actions example\n- name: Lint documentation\n run: fmd-lint --openapi openapi.json --docs docs/api\n```\n\nFor complete documentation, see [docs/fmd-lint.md](docs/fmd-lint.md). For configuration file details, see [docs/configuration.md](docs/configuration.md).\n\n## Advanced Features\n\n### General Documentation\n\nFastMarkDocs supports \"general documentation\" that provides global information about your API. This content is included in the OpenAPI schema's `info.description` field and appears at the top of your API documentation.\n\n#### How General Docs Work\n\n1. **Default File**: Create a `general_docs.md` file in your docs directory\n2. **Custom File**: Specify a different file using the `general_docs_file` parameter\n3. **Global Content**: The content appears in the API overview, not in individual endpoints\n\n#### Example General Documentation\n\nCreate a file `docs/api/general_docs.md`:\n\n```markdown\n# API Overview\n\nWelcome to our comprehensive API documentation. This API provides access to user management, order processing, and analytics features.\n\n## Authentication\n\nAll API endpoints require authentication using Bearer tokens:\n\n```bash\ncurl -H \"Authorization: Bearer YOUR_TOKEN\" https://api.example.com/users\n```\n\n## Rate Limiting\n\nAPI requests are limited to 1000 requests per hour per API key.\n\n## Error Handling\n\nOur API uses standard HTTP status codes and returns JSON error responses:\n\n```json\n{\n \"error\": \"invalid_request\",\n \"message\": \"The request is missing required parameters\"\n}\n```\n\n## Support\n\nFor API support, contact: api-support@example.com\n```\n\n#### Using General Documentation\n\n```python\nfrom fastmarkdocs import enhance_openapi_with_docs\n\n# Default: Uses general_docs.md if it exists\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\"\n)\n\n# Custom general docs file\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n general_docs_file=\"api_overview.md\"\n)\n\n# Disable general docs by passing None\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n general_docs_file=None\n)\n```\n\n#### General Docs with MarkdownDocumentationLoader\n\n```python\nfrom fastmarkdocs import MarkdownDocumentationLoader\n\n# Load with custom general docs\nloader = MarkdownDocumentationLoader(\n docs_directory=\"docs/api\",\n general_docs_file=\"custom_overview.md\"\n)\n\ndocs = loader.load_documentation()\n\n# Access general docs content (internal use)\nif hasattr(loader, '_general_docs_content'):\n print(\"General docs loaded:\", loader._general_docs_content is not None)\n```\n\n### Authentication Schemes\n\nFastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:\n\n```python\nfrom fastmarkdocs import enhance_openapi_with_docs, CodeSampleGenerator\n\n# Configure automatic authentication headers\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n base_url=\"https://api.example.com\",\n # Automatically adds appropriate auth headers to all code samples\n authentication_schemes=[\"bearer\"] # Options: \"bearer\", \"api_key\", \"basic\"\n)\n\n# For more control, use CodeSampleGenerator directly\ngenerator = CodeSampleGenerator(\n base_url=\"https://api.example.com\",\n authentication_schemes=[\"bearer\", \"api_key\"], # Supports multiple schemes\n custom_headers={\"User-Agent\": \"MyApp/1.0\"}\n)\n```\n\n**Supported Authentication Schemes:**\n- `\"bearer\"` - Adds `Authorization: Bearer YOUR_TOKEN_HERE` header\n- `\"api_key\"` - Adds `X-API-Key: YOUR_API_KEY_HERE` header \n- `\"basic\"` - Adds `Authorization: Basic YOUR_CREDENTIALS_HERE` header\n\n### Server URLs and Multi-Environment Support\n\nConfigure multiple server URLs for different environments:\n\n```python\nfrom fastmarkdocs import enhance_openapi_with_docs\n\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n base_url=\"https://api.example.com\", # Primary server\n server_urls=[ # Additional servers for code samples\n \"https://api.example.com\",\n \"https://staging-api.example.com\", \n \"https://dev-api.example.com\"\n ]\n)\n```\n\n### Custom Code Generation\n\n```python\nfrom fastmarkdocs import CodeSampleGenerator\nfrom fastmarkdocs.types import CodeLanguage\n\ngenerator = CodeSampleGenerator(\n base_url=\"https://api.example.com\",\n code_sample_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],\n custom_headers={\"Authorization\": \"Bearer token\"},\n authentication_schemes=[\"bearer\"], # Automatic auth headers\n server_urls=[\"https://api.example.com\", \"https://staging-api.example.com\"],\n cache_enabled=True # Enable caching for better performance\n)\n\n# Generate samples for a specific endpoint\nsamples = generator.generate_samples_for_endpoint(endpoint_data)\n```\n\n### Custom Code Templates\n\nCreate custom templates for specific languages with dynamic variables:\n\n```python\nfrom fastmarkdocs import CodeSampleGenerator\nfrom fastmarkdocs.types import CodeLanguage\n\n# Define custom templates with variables\ncustom_templates = {\n CodeLanguage.PYTHON: \"\"\"\n# {summary}\n# {description}\n\nimport requests\n\ndef call_{method_lower}_api():\n response = requests.{method_lower}(\n '{url}',\n headers={{'Authorization': 'Bearer YOUR_TOKEN'}}\n )\n return response.json()\n\n# Usage\nresult = call_{method_lower}_api()\nprint(result)\n\"\"\",\n CodeLanguage.BASH: \"\"\"\n#!/bin/bash\n# {summary}\n\ncurl -X {method} \\\\\n '{url}' \\\\\n -H 'Authorization: Bearer YOUR_TOKEN' \\\\\n -H 'Content-Type: application/json'\n\"\"\"\n}\n\ngenerator = CodeSampleGenerator(\n base_url=\"https://api.example.com\",\n custom_templates=custom_templates\n)\n```\n\n**Available Template Variables:**\n- `{method}` - HTTP method (GET, POST, etc.)\n- `{method_lower}` - HTTP method in lowercase\n- `{path}` - API endpoint path\n- `{url}` - Complete URL\n- `{base_url}` - Base URL\n- `{summary}` - Endpoint summary\n- `{description}` - Endpoint description\n\n### Advanced Loader Configuration\n\n```python\nfrom fastmarkdocs import MarkdownDocumentationLoader\nfrom fastmarkdocs.types import CodeLanguage\n\nloader = MarkdownDocumentationLoader(\n docs_directory=\"docs/api\",\n supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samples\n file_patterns=[\"*.md\", \"*.markdown\"], # File types to process\n encoding=\"utf-8\",\n recursive=True, # Search subdirectories\n cache_enabled=True, # Enable caching for performance\n cache_ttl=3600, # Cache for 1 hour\n general_docs_file=\"api_overview.md\" # Custom general docs file\n)\n```\n\n## API Reference\n\n### Core Functions\n\n#### `enhance_openapi_with_docs()`\n\nEnhance an OpenAPI schema with markdown documentation.\n\n**Parameters:**\n- `openapi_schema` (dict): The original OpenAPI schema\n- `docs_directory` (str): Path to markdown documentation directory\n- `base_url` (str, optional): Base URL for code samples (default: \"https://api.example.com\")\n- `include_code_samples` (bool, optional): Whether to include code samples (default: True)\n- `include_response_examples` (bool, optional): Whether to include response examples (default: True)\n- `code_sample_languages` (list[CodeLanguage], optional): Languages for code generation\n- `custom_headers` (dict, optional): Custom headers for code samples\n- `app_title` (str, optional): Override the application title\n- `app_description` (str, optional): Application description to include\n- `api_links` (list[APILink], optional): List of links to other APIs\n- `general_docs_file` (str, optional): Path to general documentation file (default: \"general_docs.md\" if found)\n\n**Returns:** Enhanced OpenAPI schema (dict)\n\n**Basic Example:**\n```python\nfrom fastmarkdocs import enhance_openapi_with_docs\n\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n base_url=\"https://api.example.com\",\n include_code_samples=True,\n include_response_examples=True,\n general_docs_file=\"general_docs.md\" # Optional: specify general documentation\n)\n```\n\n**Example with API Links:**\n```python\nfrom fastmarkdocs import APILink, enhance_openapi_with_docs\n\n# Define links to other APIs in your system\napi_links = [\n APILink(url=\"/docs\", description=\"Authorization\"),\n APILink(url=\"/api/storage/docs\", description=\"Storage\"),\n APILink(url=\"/api/monitoring/docs\", description=\"Monitoring\"),\n]\n\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n app_title=\"My API Gateway\",\n app_description=\"Authorization and access control service\",\n api_links=api_links,\n general_docs_file=\"general_docs.md\" # Optional: include general documentation\n)\n```\n\n**Example with General Documentation:**\n```python\n# Using default general_docs.md file\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\"\n # Automatically includes content from docs/api/general_docs.md\n)\n\n# Using custom general documentation file\nenhanced_schema = enhance_openapi_with_docs(\n openapi_schema=app.openapi(),\n docs_directory=\"docs/api\",\n general_docs_file=\"custom_overview.md\"\n)\n```\n\n### Configuration Classes\n\n#### `MarkdownDocumentationConfig`\n\nConfiguration for markdown documentation loading.\n\n```python\nfrom fastmarkdocs import MarkdownDocumentationConfig, CodeLanguage\n\nconfig = MarkdownDocumentationConfig(\n docs_directory=\"docs/api\",\n base_url_placeholder=\"https://api.example.com\",\n supported_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],\n file_patterns=[\"*.md\", \"*.markdown\"],\n encoding=\"utf-8\",\n recursive=True,\n cache_enabled=True,\n cache_ttl=3600 # 1 hour\n)\n```\n\n#### `OpenAPIEnhancementConfig`\n\nConfiguration for OpenAPI schema enhancement.\n\n```python\nfrom fastmarkdocs import OpenAPIEnhancementConfig, CodeLanguage\n\nconfig = OpenAPIEnhancementConfig(\n include_code_samples=True,\n include_response_examples=True,\n include_parameter_examples=True,\n code_sample_languages=[CodeLanguage.CURL, CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT],\n base_url=\"https://api.example.com\",\n server_urls=[\"https://api.example.com\", \"https://staging-api.example.com\"],\n custom_headers={\"Authorization\": \"Bearer {token}\"},\n authentication_schemes=[\"bearerAuth\", \"apiKey\"]\n)\n```\n\n### Types and Data Classes\n\n#### `APILink`\n\nRepresents a link to another API in your system.\n\n```python\nfrom fastmarkdocs import APILink\n\n# Create API links\napi_link = APILink(\n url=\"/api/storage/docs\",\n description=\"Storage API\"\n)\n\n# Use in enhance_openapi_with_docs\napi_links = [\n APILink(url=\"/docs\", description=\"Main API\"),\n APILink(url=\"/admin/docs\", description=\"Admin API\"),\n]\n```\n\n#### `DocumentationData`\n\nContainer for all documentation data loaded from markdown files.\n\n```python\nfrom fastmarkdocs import DocumentationData, EndpointDocumentation\n\ndata = DocumentationData(\n endpoints=[], # List of EndpointDocumentation\n global_examples=[], # List of CodeSample\n metadata={} # Dict of metadata\n)\n\n# Access endpoints\nfor endpoint in data.endpoints:\n print(f\"{endpoint.method} {endpoint.path}\")\n```\n\n#### `EndpointDocumentation`\n\nDocumentation for a single API endpoint.\n\n```python\nfrom fastmarkdocs import EndpointDocumentation, HTTPMethod, CodeSample\n\nendpoint = EndpointDocumentation(\n path=\"/users/{user_id}\",\n method=HTTPMethod.GET,\n summary=\"Get user by ID\",\n description=\"Retrieve a specific user by their unique identifier\",\n code_samples=[], # List of CodeSample\n response_examples=[], # List of ResponseExample\n parameters=[], # List of ParameterDocumentation\n tags=[\"users\"],\n deprecated=False\n)\n```\n\n#### `CodeSample`\n\nRepresents a code sample in a specific language.\n\n```python\nfrom fastmarkdocs import CodeSample, CodeLanguage\n\nsample = CodeSample(\n language=CodeLanguage.PYTHON,\n code=\"\"\"\nimport requests\n\nresponse = requests.get(\"https://api.example.com/users/123\")\nuser = response.json()\n\"\"\",\n description=\"Get user by ID using requests library\",\n title=\"Python Example\"\n)\n```\n\n### Core Classes\n\n#### `MarkdownDocumentationLoader`\n\nLoad and process markdown documentation files from a directory.\n\n**Parameters:**\n- `docs_directory` (str): Path to markdown documentation directory (default: \"docs\")\n- `base_url_placeholder` (str): Placeholder URL for code samples (default: \"https://api.example.com\")\n- `supported_languages` (list[CodeLanguage], optional): Languages to support for code samples\n- `file_patterns` (list[str], optional): File patterns to match (default: [\"*.md\", \"*.markdown\"])\n- `encoding` (str): File encoding (default: \"utf-8\")\n- `recursive` (bool): Whether to search directories recursively (default: True)\n- `cache_enabled` (bool): Whether to enable caching (default: True)\n- `cache_ttl` (int): Cache time-to-live in seconds (default: 3600)\n- `general_docs_file` (str, optional): Path to general documentation file\n\n**Methods:**\n- `load_documentation()` \u2192 `DocumentationData`: Load all documentation\n- `parse_markdown_file(file_path)` \u2192 `dict`: Parse a single markdown file\n- `clear_cache()`: Clear the documentation cache\n- `get_stats()` \u2192 `dict`: Get loading statistics\n\n```python\nfrom fastmarkdocs import MarkdownDocumentationLoader, CodeLanguage\n\nloader = MarkdownDocumentationLoader(\n docs_directory=\"docs/api\",\n recursive=True,\n cache_enabled=True,\n cache_ttl=3600,\n supported_languages=[CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT, CodeLanguage.CURL],\n general_docs_file=\"overview.md\"\n)\n\n# Load all documentation\ndocs = loader.load_documentation()\n\n# Get statistics\nstats = loader.get_stats()\nprint(f\"Loaded {stats['total_endpoints']} endpoints\")\n```\n\n#### `CodeSampleGenerator`\n\nGenerate code samples for API endpoints in multiple languages.\n\n**Parameters:**\n- `base_url` (str): Base URL for code samples (default: \"https://api.example.com\")\n- `custom_headers` (dict[str, str]): Custom headers to include\n- `code_sample_languages` (list[CodeLanguage]): Languages to generate\n- `custom_templates` (dict[CodeLanguage, str]): Custom code templates\n\n**Methods:**\n- `generate_samples_for_endpoint(endpoint_data)` \u2192 `list[CodeSample]`: Generate samples for an endpoint\n- `generate_curl_sample(method, url, headers, body)` \u2192 `CodeSample`: Generate cURL sample\n- `generate_python_sample(method, url, headers, body)` \u2192 `CodeSample`: Generate Python sample\n\n```python\nfrom fastmarkdocs import CodeSampleGenerator, CodeLanguage\n\ngenerator = CodeSampleGenerator(\n base_url=\"https://api.example.com\",\n custom_headers={\"Authorization\": \"Bearer {token}\", \"Content-Type\": \"application/json\"},\n code_sample_languages=[CodeLanguage.CURL, CodeLanguage.PYTHON, CodeLanguage.JAVASCRIPT],\n custom_templates={\n CodeLanguage.PYTHON: \"\"\"\nimport requests\n\ndef {method_lower}_{path_safe}():\n headers = {headers}\n response = requests.{method_lower}(\"{url}\", headers=headers)\n return response.json()\n\"\"\"\n }\n)\n\n# Generate samples for an endpoint\nsamples = generator.generate_samples_for_endpoint({\n \"method\": \"GET\",\n \"path\": \"/users/{user_id}\",\n \"parameters\": {\"user_id\": 123}\n})\n```\n\n#### `OpenAPIEnhancer`\n\nEnhance OpenAPI schemas with documentation data and code samples.\n\n**Parameters:**\n- `base_url` (str): Base URL for code samples\n- `custom_headers` (dict[str, str]): Custom headers for code samples\n- `code_sample_languages` (list[CodeLanguage]): Languages for code generation\n- `include_code_samples` (bool): Whether to include code samples (default: True)\n- `include_response_examples` (bool): Whether to include response examples (default: True)\n\n**Methods:**\n- `enhance_openapi_schema(schema, documentation_data)` \u2192 `dict`: Enhance a schema\n- `add_code_samples_to_operation(operation, endpoint)`: Add code samples to an operation\n- `add_response_examples_to_operation(operation, endpoint)`: Add response examples\n\n```python\nfrom fastmarkdocs import OpenAPIEnhancer, CodeLanguage\n\nenhancer = OpenAPIEnhancer(\n base_url=\"https://api.example.com\",\n custom_headers={\"X-API-Key\": \"your-key\"},\n code_sample_languages=[CodeLanguage.PYTHON, CodeLanguage.GO],\n include_code_samples=True,\n include_response_examples=True\n)\n\n# Enhance schema\nenhanced = enhancer.enhance_openapi_schema(openapi_schema, documentation_data)\n```\n\n## Supported Languages\n\nThe library supports code generation for:\n\n- **Python** - Using `requests` library\n- **JavaScript** - Using `fetch` API\n- **TypeScript** - With proper type annotations\n- **Go** - Using `net/http` package\n- **Java** - Using `HttpURLConnection`\n- **PHP** - Using `cURL`\n- **Ruby** - Using `net/http`\n- **C#** - Using `HttpClient`\n- **cURL** - Command-line examples\n\n## Error Handling\n\nThe library provides comprehensive error handling:\n\n```python\nfrom fastmarkdocs.exceptions import (\n DocumentationLoadError,\n CodeSampleGenerationError,\n OpenAPIEnhancementError,\n ValidationError\n)\n\ntry:\n docs = loader.load_documentation()\nexcept DocumentationLoadError as e:\n print(f\"Failed to load documentation: {e}\")\n```\n\n## Testing\n\nRun the test suite:\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=fastmarkdocs\n\n# Run specific test categories\npytest -m unit\npytest -m integration\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes\n4. Add tests for your changes\n5. Run the test suite (`pytest`)\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to the branch (`git push origin feature/amazing-feature`)\n8. Open a Pull Request\n\n## Documentation Development\n\nTo build and test the documentation locally:\n\n```bash\n# First time setup (install Ruby dependencies)\n./build-docs.sh setup\n\n# Build and serve locally with live reload\n./build-docs.sh serve\n\n# Or using Make\nmake -f Makefile.docs docs-serve\n```\n\nThe documentation will be available at `http://localhost:4001` with automatic reloading when you make changes.\n\nSee [src/docs/BUILD.md](src/docs/BUILD.md) for detailed documentation build instructions.\n\n## Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/yourusername/fastmarkdocs.git\ncd fastmarkdocs\n\n# Install Poetry (if not already installed)\ncurl -sSL https://install.python-poetry.org | python3 -\n\n# Install dependencies\npoetry install\n\n# Activate virtual environment\npoetry shell\n\n# Run tests\npytest\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Changelog\n\nSee [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes.\n\n## Support\n\n- \ud83d\udcd6 [Documentation](https://github.com/danvatca/fastmarkdocs)\n- \ud83d\udc1b [Issue Tracker](https://github.com/danvatca/fastmarkdocs/issues)\n- \ud83d\udcac [Discussions](https://github.com/danvatca/fastmarkdocs/discussions)\n\n## Related Projects\n\n- [FastAPI](https://fastapi.tiangolo.com/) - The web framework this library enhances\n- [OpenAPI](https://swagger.io/specification/) - The specification this library extends\n- [Swagger UI](https://swagger.io/tools/swagger-ui/) - The UI that displays the enhanced documentation\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A powerful library for enhancing FastAPI applications with rich markdown-based API documentation",
"version": "0.4.2",
"project_urls": {
"Bug Tracker": "https://github.com/danvatca/fastmarkdocs/issues",
"Changelog": "https://github.com/danvatca/fastmarkdocs/blob/main/CHANGELOG.md",
"Documentation": "https://github.com/danvatca/fastmarkdocs",
"Homepage": "https://github.com/danvatca/fastmarkdocs",
"Repository": "https://github.com/danvatca/fastmarkdocs"
},
"split_keywords": [
"fastapi",
" markdown",
" documentation",
" openapi",
" api",
" docs"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "941163f13e3c0a2372bfc42b676fe2875d001208cc878f66477fab791d669acb",
"md5": "9e382664d92ae45a2d2cd2a39d6cee06",
"sha256": "ed8195b5293b7e5299f6e602885a61448ad56cee21fdc9b8ba9fe261c3112940"
},
"downloads": -1,
"filename": "fastmarkdocs-0.4.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9e382664d92ae45a2d2cd2a39d6cee06",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9.2",
"size": 76144,
"upload_time": "2025-09-10T16:19:10",
"upload_time_iso_8601": "2025-09-10T16:19:10.885417Z",
"url": "https://files.pythonhosted.org/packages/94/11/63f13e3c0a2372bfc42b676fe2875d001208cc878f66477fab791d669acb/fastmarkdocs-0.4.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "896a84f039e4ff5f6a1329749b0023b4aa6012be200e0bca9e01e9c6cc3dcf81",
"md5": "9a4cb6b03465dff980a3f3c1e1b32f09",
"sha256": "2b817c0af913925597ce9a49bd2d9e46d7edba57d07e71336d39a4bdaa91fd82"
},
"downloads": -1,
"filename": "fastmarkdocs-0.4.2.tar.gz",
"has_sig": false,
"md5_digest": "9a4cb6b03465dff980a3f3c1e1b32f09",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9.2",
"size": 76725,
"upload_time": "2025-09-10T16:19:12",
"upload_time_iso_8601": "2025-09-10T16:19:12.306975Z",
"url": "https://files.pythonhosted.org/packages/89/6a/84f039e4ff5f6a1329749b0023b4aa6012be200e0bca9e01e9c6cc3dcf81/fastmarkdocs-0.4.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-10 16:19:12",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "danvatca",
"github_project": "fastmarkdocs",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "fastmarkdocs"
}