Publish Python code-linked documentation with MkDocs + mkdocstrings#

I experienced automatically generating API documentation from Python code and publishing it on GitHub Pages using MkDocs, so I would like to summarize the steps and impressions.

overview#

  • Tools used: MkDocs, mkdocstrings, Poetry

  • Purpose: Deploy Python code docstrings as API documentation on Markdown and try them out until publishing.

  • Results: We were able to create and publish an easy-to-read document that displays function arguments, return values, etc. in an orderly manner in a table format.

Installation steps#

  1. Initializing the Poetry project:

    poetry init
    
  2. Installing required packages:

    poetry add --group docs mkdocs 'mkdocstrings[python]' mkdocs-material
    
  3. Initializing the MkDocs project:

    poetry run mkdocs new docs
    
  4. Editing mkdocs.yml:

    site_name: My Project Docs
    theme:
      name: material
    nav:
      - Home: index.md
      - API: api.md
    plugins:
      - search
      - mkdocstrings:
          default_handler: python
    
  5. Create API documentation file (docs/api.md):

    ::: myproject.hello
    
  6. Creating sample code (myproject/hello.py):

    def greet(name: str) -> str:
        """名前に挨拶を返します
    
        Args:
            name (str): 対象の名前
    
        Returns:
            str: 挨拶文
        """
        return f"Hello, {name}!"
    
  7. Check locally:

    poetry run mkdocs serve
    
  8. Publishing to GitHub Pages:

    poetry run mkdocs gh-deploy
    

thoughts#

  • Conveniently formats the docstring automatically and displays the API specification in a very easy-to-read tabular format.

  • Since it can be edited based on Markdown, I felt it was easier to install and modify than Sphinx.

  • It is highly linked with the code, and there is a sense of security that any changes can be immediately reflected in the document.

  • Through mkdocstrings, I realized once again the value of type hints and Google-style docstrings.

In the future, we would like to create a template for this configuration and introduce an automatic update mechanism through CI coordination.

Article information

author:

Mr. Takagi

Post date:

2025-05-23