sphinx-autoapi A new approach to API documentation in Sphinx

Description

Sphinx AutoAPI provides « autodoc » style documentation for multiple programming languages without needing to load, run, or import the project being documented.

In contrast to the traditional Sphinx autodoc, which is Python-only and uses code imports, AutoAPI finds and generates documentation by parsing source code.

Autoapi setup

After trying both autodoc/autosummary and Sphinx AutoAPI, I opted to use the latter. Here are the main reasons behind this choice:

  • Autosummary does not generate TOC entries for API elements such as classes/modules and their members . This is due to a long-standing Sphinx limitation. Autoapi works around this limitation (albeit imperfectly, as we’ll later note).

  • Autosummary defaults to not generating anything and is in my experience frustrating to setup. In contrast, autoapi produces usable output out-of-the-box .

  • Jinja Templates are easier to write thanks to the rich “mapper” objects AutoAPI provides after parsing your code (see the AutoAPI objects section below).

Basics

Setting up Sphinx AutoAPI is covered in their documentation. It boils down to the following steps.

Install the sphinx-autoapi package:

$ pip install sphinx-autoapi

Add AutoAPI it to the Sphinx extension list:

extensions = [
    ...,
    'autoapi.extension',
]

List your package directories (or the directory containing them) and set basic options:

autoapi_dirs = ['../mypackage']
autoapi_type = "python"

Add the generated documentation to your index.rst toctree:

.. toctree::
   :maxdepth: 3

   ...
   autoapi/index

Setting up jinja templates

../../_images/jinja_template_logo.png

We will customise Sphinx AutoAPI’s jinja default templates.

The easiest is to copy Sphinx AutoAPI’s default templates in your project to serve as a starting point.

First, run the following commands (adjusting for your Python version) from your documentation directory:

$ mkdir _templates
$ mkdir _template/autoapi
$ cp $VIRTUAL_ENV/lib/python3.10/site-packages/autoapi/templates/index.rst _templates/autoapi/
$ cp -r $VIRTUAL_ENV/lib/python3.10/site-packages/autoapi/templates/python _templates/autoapi/

Then, tell Sphinx AutoAPI of its template directory in your conf.py file:

autoapi_template_dir = "_templates/autoapi"

A useful tip is to make a Git commit just after copying the built-in templates, such that you can track (and revert) your modifications.

I’ve used this extensively while working on my templates.

At this point, I suggest spending some time to become acquainted with the built-in autoapi jinja templates and how they are organised and implemented.

If you haven’t used it before, it is also useful to review the Jinja templating language documentation .

Issues

Customization of sphinx-api by Antoine Beyeler with jinja templates