Fetch Data from REST API in mkdocs

440 Views Asked by At

I am trying to create to port old wiki pages to a centralized location. Some of the data however needs to fetched in runtime from a REST Server.

For this purpose I have found a hacky solution of using mkdocs-macros plugin. And then create a custom module in the main.py file where I am using the python requests module to perform simple HTTP GET requests and return the required data.

Is there a better/proper way to do the above functionality in mkdocs?

1

There are 1 best solutions below

0
On

I am the author of mkdocs-macros. Using macros would be actually, a "mkdoc-ic" way to develop your application. mkdocs-macros is listed in the official catalog of mkdocs plugins, as a first choice in the category "Code execution, variables & templating".

If you want to call a REST API, you can indeed use a Python module main.pyand follow the standard pattern, as explained e.g. on the Real Python page.

Something like:

import requests

API_URL = "https://..."

def define_env(env):
    """
    This is the hook for the functions
    """

    @env.macro
    def uptime(machine_name: string) -> string:
        response = requests.get(f"{API_URL}?{machine_name}")
        fields = response.json()
        return fields['uptime']

Then you could use this call in your markdown page:

At this moment the uptime of our server has been {{ uptime('foo') }}.

If you wish to build a reusable application that you can treat as a github projet, easily distribute and install (even through pypi), etc. I suggest to write it not as a module, but as a pluglet.