Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

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.

PyPI versionPython SupportLicense: MITCIcodecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🏷️ Smart Section Descriptions: Automatically extract section descriptions from markdown Overview sections
🌍 Multi-language Code Samples: Generate code examples in Python, JavaScript, TypeScript, Go, Java, PHP, Ruby, C#, and cURL
📝 Markdown-First: Write documentation in familiar markdown format
🔗 API Cross-References: Include links to other APIs in your system with automatic formatting
🎨 Customizable Templates: Use custom templates for code generation
High Performance: Built-in caching and optimized processing
🧪 Well Tested: Comprehensive test suite with 100+ tests
🔍 Documentation Linting: Built-in fmd-lint tool to analyze and improve documentation quality
🏗️ Documentation Scaffolding: fmd-init tool to bootstrap documentation for existing projects

Quick Start

Installation

Basic Installation

pip install fastmarkdocs

Development Installation

# 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:

# 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

fromfastapiimportFastAPIfromfastmarkdocsimportenhance_openapi_with_docsapp=FastAPI()
# Enhance your OpenAPI schema with markdown documentationenhanced_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 schemaapp.openapi_schema=enhanced_schema

Advanced Usage with API Links

For microservice architectures where you want to link between different APIs:

fromfastapiimportFastAPIfromfastapi.openapi.utilsimportget_openapifromfastmarkdocsimportAPILink, enhance_openapi_with_docsapp=FastAPI()
defcustom_openapi():
ifapp.openapi_schema:
returnapp.openapi_schema# Define links to other APIs in your systemapi_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 linksenhanced_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_schemareturnapp.openapi_schemaapp.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):

# 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

importrequestsresponse=requests.get("https://api.example.com/users")
users=response.json()
constresponse=awaitfetch('https://api.example.com/users');constusers=awaitresponse.json();

Section: User Management


## Smart Section Descriptions
FastMarkDocs automatically extracts rich section 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.
Section: User Management
### POST /users
Create a new user account.
Section: User Management

docs/api/authentication.md:

# 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.
Section: Authentication
### POST /auth/logout
Logout a user and invalidate the session.
Section: Authentication

Generated OpenAPI Enhancement

FastMarkDocs automatically creates this in your OpenAPI schema:

{
"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 sections 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:

# 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:

# FastMarkDocs Linter Configuration# Generated automatically by fmd-initexclude:
endpoints:
- path: "^/(health|ready|live|ping)"methods: [".*"]
- path: "^/metrics"methods: ["GET"]openapi: "./openapi.json"docs:
- "./docs"recursive: truebase_url: "https://api.example.com"

Documentation Linting with fmd-lint

FastMarkDocs includes a powerful documentation linter that helps you maintain high-quality API documentation:

# 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:

exclude:
endpoints:
- path: "^/static/.*"methods: ["GET"]
- path: "^/health"methods: [".*"]spec_generator:
- "poetry run python ./generate_openapi.py"docs:
- "./docs/api"recursive: truebase_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

# GitHub Actions example
- name: Lint documentationrun: fmd-lint --openapi openapi.json --docs docs/api

For complete documentation, see docs/fmd-lint.md. For configuration file details, see 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:

# 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:

{
"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

fromfastmarkdocsimportMarkdownDocumentationLoader# Load with custom general docsloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
general_docs_file="custom_overview.md"
)
docs=loader.load_documentation()
# Access general docs content (internal use)ifhasattr(loader, '_general_docs_content'):
print("General docs loaded:", loader._general_docs_contentisnotNone)

Authentication Schemes

FastMarkDocs can automatically add authentication headers to generated code samples based on your API's authentication requirements:

fromfastmarkdocsimportenhance_openapi_with_docs, CodeSampleGenerator# Configure automatic authentication headersenhanced_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 samplesauthentication_schemes=["bearer"] # Options: "bearer", "api_key", "basic"
)
# For more control, use CodeSampleGenerator directlygenerator=CodeSampleGenerator(
base_url="https://api.example.com",
authentication_schemes=["bearer", "api_key"], # Supports multiple schemescustom_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_schema=enhance_openapi_with_docs(
openapi_schema=app.openapi(),
docs_directory="docs/api",
base_url="https://api.example.com", # Primary serverserver_urls=[ # Additional servers for code samples"https://api.example.com",
"https://staging-api.example.com", "https://dev-api.example.com"
]
)

Custom Code Generation

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguagegenerator=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 headersserver_urls=["https://api.example.com", "https://staging-api.example.com"],
cache_enabled=True# Enable caching for better performance
)
# Generate samples for a specific endpointsamples=generator.generate_samples_for_endpoint(endpoint_data)

Custom Code Templates

Create custom templates for specific languages with dynamic variables:

fromfastmarkdocsimportCodeSampleGeneratorfromfastmarkdocs.typesimportCodeLanguage# Define custom templates with variablescustom_templates= {
CodeLanguage.PYTHON: """# {summary}# {description}import requestsdef call_{method_lower}_api(): response = requests.{method_lower}( '{url}', headers={{'Authorization': 'Bearer YOUR_TOKEN'}} ) return response.json()# Usageresult = 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

fromfastmarkdocsimportMarkdownDocumentationLoaderfromfastmarkdocs.typesimportCodeLanguageloader=MarkdownDocumentationLoader(
docs_directory="docs/api",
supported_languages=[CodeLanguage.PYTHON, CodeLanguage.CURL], # Filter code samplesfile_patterns=["*.md", "*.markdown"], # File types to processencoding="utf-8",
recursive=True, # Search subdirectoriescache_enabled=True, # Enable caching for performancecache_ttl=3600, # Cache for 1 hourgeneral_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:

fromfastmarkdocsimportenhance_openapi_with_docsenhanced_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:

fromfastmarkdocsimportAPILink, enhance_openapi_with_docs# Define links to other APIs in your systemapi_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:

# Using default general_docs.md fileenhanced_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 fileenhanced_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.

fromfastmarkdocsimportMarkdownDocumentationConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportOpenAPIEnhancementConfig, CodeLanguageconfig=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.

fromfastmarkdocsimportAPILink# Create API linksapi_link=APILink(
url="/api/storage/docs",
description="Storage API"
)
# Use in enhance_openapi_with_docsapi_links= [
APILink(url="/docs", description="Main API"),
APILink(url="/admin/docs", description="Admin API"),
]

DocumentationData

Container for all documentation data loaded from markdown files.

fromfastmarkdocsimportDocumentationData, EndpointDocumentationdata=DocumentationData(
endpoints=[], # List of EndpointDocumentationglobal_examples=[], # List of CodeSamplemetadata={} # Dict of metadata
)
# Access endpointsforendpointindata.endpoints:
print(f"{endpoint.method}{endpoint.path}")

EndpointDocumentation

Documentation for a single API endpoint.

fromfastmarkdocsimportEndpointDocumentation, HTTPMethod, CodeSampleendpoint=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 CodeSampleresponse_examples=[], # List of ResponseExampleparameters=[], # List of ParameterDocumentationtags=["users"],
deprecated=False
)

CodeSample

Represents a code sample in a specific language.

fromfastmarkdocsimportCodeSample, CodeLanguagesample=CodeSample(
language=CodeLanguage.PYTHON,
code="""import requestsresponse = 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
fromfastmarkdocsimportMarkdownDocumentationLoader, CodeLanguageloader=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 documentationdocs=loader.load_documentation()
# Get statisticsstats=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
fromfastmarkdocsimportCodeSampleGenerator, CodeLanguagegenerator=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 requestsdef {method_lower}_{path_safe}(): headers = {headers} response = requests.{method_lower}("{url}", headers=headers) return response.json()"""
}
)
# Generate samples for an endpointsamples=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
fromfastmarkdocsimportOpenAPIEnhancer, CodeLanguageenhancer=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 schemaenhanced=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:

fromfastmarkdocs.exceptionsimport (
DocumentationLoadError,
CodeSampleGenerationError,
OpenAPIEnhancementError,
ValidationError
)
try:
docs=loader.load_documentation()
exceptDocumentationLoadErrorase:
print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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:

# 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 for detailed documentation build instructions.

Development Setup

# 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 file for details.

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

Related Projects

  • FastAPI - The web framework this library enhances
  • OpenAPI - The specification this library extends
  • Swagger UI - The UI that displays the enhanced documentation

About

Library for enhancing FastAPI applications with rich markdown-based API documentation.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages