Skip to content

Instantly share code, notes, and snippets.

@vasansr
Last active March 30, 2023 04:38
Show Gist options
  • Save vasansr/026ef767b63ee3b62e664fd2a5d10ad6 to your computer and use it in GitHub Desktop.
Save vasansr/026ef767b63ee3b62e664fd2a5d10ad6 to your computer and use it in GitHub Desktop.
Python script to generate markdown format documentation from Thunder Client collections.
GENERATED=api-docs/.generated
THUNDER_FILES=thunder-tests/thunderclient.json
$(GENERATED): $(THUNDER_FILES)
python gen-api-docs.py
touch $(GENERATED)
#
# Generate the documentation in a markdown format from the thunderclient.json file
# This collects interesting stuff like Parameters, Headers etc. from the request,
# and appends the "docs" section.
#
import json
import re
def slugify(text):
text = text.lower()
return re.sub(r'[\W_]+', '-', text).strip("-")
def write_collection(f, id, requests):
f.write(f"# Index\n\n")
for r in requests:
if r['colId'] != id:
continue
name = r['name']
slug = slugify(name)
f.write(f" * [{name}](#markdown-header-{slug})\n")
f.write("\n")
for r in requests:
# print (r['name'])
if r['colId'] != id:
continue
f.write(f"# {r['name']}\n\n")
f.write("## Endpoint\n")
url = r['url']
q = url.find('?')
if q != -1:
url = url[:q]
f.write(f"`{r['method']} {url}`\n\n")
f.write("## Headers\n")
if not 'headers' in r or len(r['headers']) == 0:
f.write("None\n")
else:
f.write("Header | Example\n")
f.write("------ | -------\n")
f.writelines(f"{h['name']} | `{h['value']}` \n" for h in r['headers'])
f.write("\n")
f.write("\n")
f.write("## Parameters\n")
if not 'params' in r or len(r['params']) == 0:
f.write("None\n")
else:
f.write("Parameter | Example\n")
f.write("--------- | -------\n")
f.writelines(f"{p['name']} | `{p['value']}`\n" for p in r['params'])
f.write("\n")
f.write("\n")
if 'body' in r:
f.write("## Post Body\n\n")
f.write("```\n")
f.write(r['body']['raw'])
f.write("\n```\n")
if 'docs' in r:
f.write(r['docs'])
f.write("\n\n")
with open("thunder-tests/thunderclient.json") as f:
requests = json.load(f)
requests.sort(key=lambda x:x['sortNum'])
with open("thunder-tests/thunderCollection.json") as f:
collections = json.load(f)
for c in collections:
name = c['colName']
id = c['_id']
# Skip test cases
if name.lower().find('test') != -1:
continue
with open(f"api-docs/{name}.md", "w") as f:
write_collection(f, id, requests)
#!/bin/sh
#
# Make sure this script is executable (chmod +x pre-commit)
# Save it in your .git/hooks directory
#
make -f docs.mk | grep -q 'up to date'
if [ $? -ne 0 ] ; then
echo
echo "=> (pre-commit hook): Adding generated API docs to the commit"
echo
git add api-docs/*
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment