API Documentation with mkdocstrings¶
mkdocstrings is a powerful plugin that automatically generates documentation from your source code docstrings, creating beautiful API references directly in your MkDocs site.
Overview¶
mkdocstrings extracts documentation from:
- Python modules - Classes, functions, methods, attributes
- Docstrings - Google, NumPy, and Sphinx styles supported
- Type hints - Full support for Python type annotations
- Cross-references - Automatic linking between documented objects
Configuration¶
Basic configuration in mkdocs.yml
:
plugins:
- mkdocstrings:
default_handler: python
handlers:
python:
options:
show_source: true
show_root_heading: true
Advanced Configuration¶
plugins:
- mkdocstrings:
default_handler: python
handlers:
python:
import:
- https://docs.python.org/3/objects.inv
options:
# Headings
show_root_heading: true
show_root_toc_entry: true
show_object_full_path: false
show_category_heading: true
show_symbol_type_heading: true
show_symbol_type_toc: true
# Members
members_order: source
group_by_category: true
show_submodules: true
# Docstrings
docstring_style: google
docstring_section_style: table
merge_init_into_class: true
show_if_no_docstring: false
# Signatures
show_signature: true
show_signature_annotations: true
separate_signature: true
line_length: 80
# Filters
filters: ["!^_"]
inherited_members: true
Usage¶
Basic Documentation¶
To document a module, use the special module.path
syntax:
Selective Documentation¶
Document specific objects:
# Calculator Class
::: mypackage.calculator.Calculator
options:
members:
- add
- subtract
- multiply
- divide
Handler Options¶
Control display per page:
Docstring Styles¶
Google Style¶
def function(param1: str, param2: int) -> bool:
"""Summary line.
Extended description of function.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of return value
Raises:
ValueError: If param2 is negative
Example:
>>> function("test", 42)
True
"""
NumPy Style¶
def function(param1: str, param2: int) -> bool:
"""
Summary line.
Extended description of function.
Parameters
----------
param1 : str
Description of param1
param2 : int
Description of param2
Returns
-------
bool
Description of return value
Raises
------
ValueError
If param2 is negative
"""
Type Annotations¶
mkdocstrings fully supports type hints:
from typing import List, Optional, Union, TypeVar, Generic
T = TypeVar('T')
class Container(Generic[T]):
"""A generic container class.
Type Parameters:
T: The type of items in the container
"""
def add(self, item: T) -> None:
"""Add an item to the container."""
pass
def get(self, index: int) -> Optional[T]:
"""Get an item by index."""
pass
Cross-References¶
Automatic Linking¶
mkdocstrings automatically creates links between documented objects:
def process_data(calc: Calculator) -> float:
"""Process data using a Calculator instance.
Args:
calc: A :class:`Calculator` instance
See Also:
- :func:`validate_input`
- :mod:`utils`
"""
Manual References¶
Create references in Markdown:
The [Calculator][src.example.calculator.Calculator] class provides
arithmetic operations. See [add()][src.example.calculator.Calculator.add]
for addition.
Best Practices¶
1. Comprehensive Docstrings¶
Write complete docstrings for all public APIs:
class APIClient:
"""Client for interacting with the API.
This client provides methods for all API endpoints with
automatic retry logic and error handling.
Attributes:
base_url: The API base URL
timeout: Request timeout in seconds
retry_count: Number of retries for failed requests
Example:
```python
client = APIClient("https://api.example.com")
response = client.get_users()
```
Note:
Authentication is handled automatically using
environment variables.
"""
2. Type Everything¶
Use type hints for better documentation:
from typing import Dict, List, Optional
def parse_config(
config_path: str,
defaults: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Parse configuration file.
Args:
config_path: Path to configuration file
defaults: Optional default values
Returns:
Parsed configuration dictionary
"""
3. Group Related Items¶
Organize your API documentation logically:
nav:
- API Reference:
- Overview: api/index.md
- Core:
- Base Classes: api/core/base.md
- Models: api/core/models.md
- Utils:
- Helpers: api/utils/helpers.md
- Validators: api/utils/validators.md
4. Use Examples¶
Include code examples in docstrings:
def complex_function(data: List[dict]) -> dict:
"""Process complex data structures.
Args:
data: List of dictionaries to process
Returns:
Processed result dictionary
Example:
Simple usage:
>>> data = [{"id": 1, "value": 10}, {"id": 2, "value": 20}]
>>> result = complex_function(data)
>>> print(result)
{"total": 30, "count": 2}
With error handling:
>>> try:
... result = complex_function([])
... except ValueError as e:
... print(f"Error: {e}")
Error: Data cannot be empty
"""
Advanced Features¶
Custom Templates¶
Override default templates in docs/overrides/
:
{# docs/overrides/partials/docstring/attributes.html #}
<table class="field-list">
<colgroup>
<col class="field-name" />
<col class="field-body" />
</colgroup>
<tbody>
{% for attribute in attributes %}
<tr class="field">
<th class="field-name">{{ attribute.name }}</th>
<td class="field-body">
{{ attribute.description }}
{% if attribute.annotation %}
<code>{{ attribute.annotation }}</code>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
Custom CSS¶
Style API documentation:
/* docs/assets/stylesheets/api.css */
.doc-class {
border-left: 3px solid var(--md-primary-fg-color);
padding-left: 1rem;
margin: 1rem 0;
}
.doc-function {
background: var(--md-code-bg-color);
padding: 0.5rem;
border-radius: 0.2rem;
}
.field-list {
width: 100%;
margin: 1rem 0;
}
.field-name {
font-weight: bold;
white-space: nowrap;
}
Handlers for Other Languages¶
While Python is the default, other handlers are available:
mkdocstrings-crystal
- Crystal languagemkdocstrings-vba
- Visual Basic for Applications- Custom handlers can be created
Integration with Other Features¶
Search¶
API documentation is fully indexed for search:
- Function names
- Parameter names
- Docstring content
- Type annotations
Navigation¶
Use mkdocs-awesome-pages for auto-generation:
Tags¶
Tag your API documentation:
Performance Tips¶
1. Lazy Loading¶
Only load modules when needed:
2. Caching¶
Enable caching for faster builds:
plugins:
- mkdocstrings:
enable_inventory: true
handlers:
python:
options:
show_source: false # Faster without source
3. Selective Documentation¶
Document only public APIs:
Troubleshooting¶
Common Issues¶
- Import errors: Ensure your package is installed
- Missing objects: Check Python path configuration
- Broken links: Verify cross-reference syntax
- Slow builds: Reduce the number of documented objects
Debug Mode¶
Enable verbose output:
Examples in This Documentation¶
See our API reference section for live examples:
- Example Module - Overview of the package
- Base Classes - Abstract and concrete base classes
- Calculator - Complete class documentation
- Utilities - Function and decorator documentation