Skip to main content

A powerful library for enhancing FastAPI applications with rich markdown-based API documentation

Project description

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 version Python Support License: MIT CI codecov

Features

Rich Documentation: Transform markdown files into comprehensive API documentation
🔧 OpenAPI Enhancement: Automatically enhance your OpenAPI/Swagger schemas
🌍 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

Quick Start

Installation

pip install fastmarkdocs

Basic Usage

from fastapi import FastAPI
from fastmarkdocs import enhance_openapi_with_docs

app = FastAPI()

# Enhance your OpenAPI schema with markdown documentation
enhanced_schema = enhance_openapi_with_docs(
    openapi_schema=app.openapi(),
    docs_directory="docs/api",
    base_url="https://api.example.com",
    custom_headers={"Authorization": "Bearer token123"}
)

# Update your app's OpenAPI schema
app.openapi_schema = enhanced_schema

Advanced Usage with API Links

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

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastmarkdocs import APILink, enhance_openapi_with_docs

app = FastAPI()

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    
    # Define links to other APIs in your system
    api_links = [
        APILink(url="/docs", description="Authorization"),
        APILink(url="/api/storage/docs", description="Storage"),
        APILink(url="/api/monitoring/docs", description="Monitoring"),
    ]
    
    openapi_schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    
    # Enhance with custom title, description, and API links
    enhanced_schema = enhance_openapi_with_docs(
        openapi_schema=openapi_schema,
        docs_directory="docs/api",
        app_title="My API Gateway",
        app_description="Authorization and access control service",
        api_links=api_links,
    )
    
    app.openapi_schema = enhanced_schema
    return app.openapi_schema

app.openapi = custom_openapi

Documentation Structure

Create markdown files in your docs directory:

docs/api/
├── users.md
├── authentication.md
└── orders.md

Example markdown file (users.md):

# 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

import requests

response = requests.get("https://api.example.com/users")
users = response.json()
const response = await fetch('https://api.example.com/users');
const users = await response.json();

## Advanced Features

### Custom Code Generation

```python
from fastmarkdocs import CodeSampleGenerator

generator = CodeSampleGenerator(
    base_url="https://api.example.com",
    custom_headers={"X-API-Key": "your-key"},
    code_sample_languages=["python", "javascript", "go"]
)

# Generate samples for a specific endpoint
samples = generator.generate_samples_for_endpoint(endpoint_data)

Template Customization

from fastmarkdocs import DocumentationLoader

loader = DocumentationLoader(
    docs_directory="docs/api",
    custom_templates={
        "python": """
import requests

def {method_lower}_{path_safe}():
    response = requests.{method_lower}("{url}")
    return response.json()
"""
    }
)

Caching Configuration

from fastmarkdocs import DocumentationLoader

loader = DocumentationLoader(
    docs_directory="docs/api",
    enable_caching=True,
    cache_ttl=3600  # 1 hour
)

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
  • custom_headers (dict, optional): Custom headers for code samples
  • code_sample_languages (list, optional): Languages for code generation
  • 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

Returns: Enhanced OpenAPI schema (dict)

Example with API Links:

from fastmarkdocs import APILink, enhance_openapi_with_docs

# Define links to other APIs in your system
api_links = [
    APILink(url="/docs", description="Authorization"),
    APILink(url="/api/storage/docs", description="Storage"),
    APILink(url="/api/monitoring/docs", description="Monitoring"),
]

enhanced_schema = enhance_openapi_with_docs(
    openapi_schema=app.openapi(),
    docs_directory="docs/api",
    app_title="My API Gateway",
    app_description="Authorization and access control service",
    api_links=api_links,
)

Types

APILink

Represents a link to another API in your system.

from fastmarkdocs import APILink

# Create API links
api_link = APILink(
    url="/api/storage/docs",
    description="Storage API"
)

# Use in enhance_openapi_with_docs
api_links = [
    APILink(url="/docs", description="Main API"),
    APILink(url="/admin/docs", description="Admin API"),
]

Classes

DocumentationLoader

Load and process markdown documentation files.

loader = DocumentationLoader(
    docs_directory="docs/api",
    enable_caching=True,
    cache_ttl=3600,
    custom_templates={}
)

# Load all documentation
docs = loader.load_documentation()

CodeSampleGenerator

Generate code samples for API endpoints.

generator = CodeSampleGenerator(
    base_url="https://api.example.com",
    custom_headers={"Authorization": "Bearer token"},
    code_sample_languages=["python", "javascript"]
)

# Generate samples
samples = generator.generate_samples_for_endpoint(endpoint)

OpenAPIEnhancer

Enhance OpenAPI schemas with documentation data.

enhancer = OpenAPIEnhancer(
    base_url="https://api.example.com",
    custom_headers={"X-API-Key": "key"},
    code_sample_languages=["python", "go"]
)

# Enhance schema
enhanced = enhancer.enhance_openapi_schema(schema, documentation)

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:

from fastmarkdocs.exceptions import (
    DocumentationLoadError,
    CodeSampleGenerationError,
    OpenAPIEnhancementError,
    ValidationError
)

try:
    docs = loader.load_documentation()
except DocumentationLoadError as e:
    print(f"Failed to load documentation: {e}")

Testing

Run the test suite:

# 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
./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:4000 with automatic reloading when you make changes.

See 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastmarkdocs-0.1.5.tar.gz (27.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastmarkdocs-0.1.5-py3-none-any.whl (28.2 kB view details)

Uploaded Python 3

File details

Details for the file fastmarkdocs-0.1.5.tar.gz.

File metadata

  • Download URL: fastmarkdocs-0.1.5.tar.gz
  • Upload date:
  • Size: 27.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for fastmarkdocs-0.1.5.tar.gz
Algorithm Hash digest
SHA256 407c3bc9efea8c90bf9619a2da265153b2f74b501fa9c9b559ee12a6c3dd2e8d
MD5 aea980803489829dc4ce28804b339f23
BLAKE2b-256 5798cd93ab19d3da65601a112430069055322e26e49367d1bb247b5cf202b8bb

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastmarkdocs-0.1.5.tar.gz:

Publisher: publish.yml on danvatca/FastMarkDocs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastmarkdocs-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: fastmarkdocs-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 28.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for fastmarkdocs-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 cc2d12773823708787b08a92b424189d327dc9b707ba5832f22a834982ac519a
MD5 8263232038729bed869577021cb8969c
BLAKE2b-256 740f3bd402356ce5dc2694f1099fc0a562ea5092488082934876741246c81f03

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastmarkdocs-0.1.5-py3-none-any.whl:

Publisher: publish.yml on danvatca/FastMarkDocs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page