TIL - Running make apidocs for Read the Docs

Posted on Mon 28 February 2022 in Dispatches • 1 min read

I was hacking on my quote service the other day, and notice that Read the Docs wasn’t building my module level documentation, which meant that anyone that wanted to look at said modules in more detail was getting a 404 error. One option was to simply make running make apidocs a part of my standard process and committing the results, but I hate the idea of leaving something that can, and should, be automated left to my memory.

A quick Google search led me to this Github issue full of fellow souls with the exact same problem. The solution, at least until RTD supports something more elegant in its configuraton file is to add the following to the end of your conf.py file.

def run_apidoc(_):
    from sphinx.ext.apidoc import main
    import os
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
    output_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "api")
    module = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "your_module_name_here")
    main(["-e", "-o", output_dir, module, "--force"])


def setup(app):
    app.connect("builder-inited", run_apidoc)

Note that this example assumes that your conf.py and all your docs live in a docs subdirectory at the root of your project. And assumes that you’re expecting the apidocs output to end up in the api/ subdirectory next to your _build/ directory.