AutoAPI

_images/logo.png

Automatic Python API reference documentation generator for Sphinx, inspired by Doxygen.

AutoAPI is a Sphinx extension that allows to automatically generate API reference documentation for Python packages (example), recursively, without any intervention from the developer. It will discover all the package modules and their public objects and document them.

Usage

  1. Install:

    pip install autoapi
    

    Or if using Virtualenv or Tox (and you should) add it to your requirements.txt (or requirements.dev.txt if you want to separate your package requirements from the development requirements).

  2. Add AutoAPI to your extensions:

    In your Sphinx conf.py configuration file add autoapi.sphinx:

    extensions = [
        'sphinx.ext.autodoc',
        'sphinx.ext.inheritance_diagram',
        'autoapi.sphinx'
    ]
    

    Make sure to have autodoc and inheritance_diagram too because the default generation template will use them.

  3. Configure AutoAPI with the root modules you want to generate documentation for:

    In your project conf.py file define the autoapi_modules dictionary variable with the module names as keys:

    autoapi_modules = {'mymodule': None}
    

    This dictionary maps the module names with the options for generation for that module:

    prune:

    bool [False] The package to document is modeled as a tree, and each submodule is a node of that tree. A node is considered relevant if it has a public interface that needs to be documented or it is required to reach a node that has a public interface. If prune is set to True, all branches that aren’t relevant will be silently ignored. If False, all branches will be generated, even for those modules that do not possess a public interface.

    override:

    bool [True] Regenerate the reference pages even if they exists. AutoAPI by default is automatic, but if you prefer to use it like autosummary_generate and create stub pages for later manual edition set the override flag to False and commit the generated pages to your version control. On the other hand, if fully automatic reference documentation generation is preferred put the output folder of this module in your version control ignore file.

    template:

    str ['module'] Template name to use. This option can be changed to use different templates for different modules. See the section Using different templates.

    output:

    str [module] Output folder to generate the documentation for this module relative to the folder where your conf.py is located. By default the output folder is the same as the module key. For example, for mymodule the following could be generated:

    .
    |-- conf.py
    `-- mymodule
        |-- mymodule.rst
        |-- mymodule.submodule.rst
        `-- mymodule.another.rst
    

    For example, a custom configuration could be:

    autoapi_modules = {
       'mymodule': {
          'override': False,
          'output': 'auto'
       }
    }
    
  4. Reference your documentation in your Sphinx project:

    Add in one of your reST source files a reference to the documentation.

    .. toctree::
       :hidden:
    
       mymodule/mymodule
    

    And, optionally, you can link to it like this:

    See the :doc:`reference documentation <mymodule/mymodule>`.
    
  5. Prepare your codebase:

    Now in your modules, put all the elements you want to document in the __all__ or the __api__ listings. See the section Documenting the code.

Documenting the code

The strict minimum:

  • List all public objects in your __all__ (preferred) or __api__.
  • Put at least a docstring with a brief in your module, in all your public classes, methods, functions and variables.

Even better:

  • Use the autodoc syntax in your docstrings (or use other that autodoc supports).

Use the following example as a guide. Check corresponding documentation produced by AutoAPI.

# -*- coding: utf-8 -*-
"""
This is my module brief line.

This is a more complete paragraph documenting my module.

- A list item.
- Another list item.

This section can use any reST syntax.
"""

A_CONSTANT = 1000
"""This is an important constant."""

YET_ANOTHER = {
    'this': 'that',
    'jam': 'eggs',
    'yet': {
        'things': [1, 2, 3, 'a'],
        'tuples': (A_CONSTANT, 4)
    }
}
"""Yet another public constant variable"""


def a_function(my_arg, another):
    """
    This is the brief description of my function.

    This is a more complete example of my function. It can include doctest,
    code blocks or any other reST structure.

    >>> a_function(10, [MyClass('a'), MyClass('b')])
    20

    :param int my_arg: The first argument of the function. Just a number.
    :param another: The other argument of the important function.
    :type another: A list of :class:`MyClass`
    :rtype: int
    :return: The length of the second argument times the first argument.
    """
    return my_arg * len(another)


class MyClass(object):
    """
    This is the brief of my main class.

    A more general description of what the class does.

    :param int param1: The first parameter of my class.
    :param param2: The second one.
    :type param2: int or float
    :var my_attribute: Just an instance attribute.
    :raises TypeError: if param2 is not None.
    """

    class_attribute = 625
    """This is a class attribute."""

    def __init__(self, param1, param2=None):
        self.param1 = param1
        if param2 is not None:
            raise TypeError()
        self.param2 = param2
        self.my_attribute = 100

    def my_method(self, param1, param2):
        """
        The brief of this method.

        This method does many many important things.

        :param int param1: A parameter.
        :param list param2: Another parameter.
        :rtype: list of int
        :return: A list of the first parameter as long a the length of the
         second parameter.
        """
        return [param1] * len(param2)


class AnotherClass(MyClass):
    """
    This another class.

    Check the nice inheritance diagram. See :class:`MyClass`.
    """


class MyException(Exception):
    """
    This is my custom exception.

    This is a more complete description of what my exception does. Again, you
    can be as verbose as you want here.
    """


__all__ = [
    'A_CONSTANT',
    'YET_ANOTHER',
    'a_function',
    'MyClass',
    'AnotherClass',
    'MyException'
]

Customizing

AutoAPI provides several ways to customize the output generated by the tool. AutoAPI uses the Jinja2 template engine for page generation.

Overriding the default template

The default template used by autoapi can be customized to meet your needs. To do so, copy the default template and put it in your templates_path (usually _templates) folder under:

<templates_path>/autoapi/module.rst

The next run Sphinx will use it for all your modules documentation generation.

Using different templates

Instead of providing a single template for all your modules you can also setup different templates for different modules. For example, for you module mymod you choose to use the template mymodtemplate. In your conf.py the following is setup:

# autoapi configuration
autoapi_modules = {
    'mymod': {'template': 'mymodtemplate'}
}

Now you need to place your template in:

<templates_path>/autoapi/mymodtemplate.rst

And AutoAPI will use it for documenting mymod only.

Improvements

This is a list of possible improvements, its doesn’t mean they are good idea or that they should be implemented.

  • Automatically hook the auto-generated files to the index document toctree.
  • Extend the __api__ key to support a dictionary so each element that requires documentation can provide attributes individually (like show special members).
  • Generate an optional module index page with a different template (called index.rst at the module generation folder).

License

Copyright (C) 2015 Carlos Jenkins <carlos@jenkins.co.cr>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.