Create an HTML version of an OpenAPI spec
I have a new project where we will be integrating with a third party API that is currently being written. Due to Conway’s Law, we are being sent new versions of the OpenAPI spec as a set of JSON files via email.
I quite like seeing the HTML rendering of an OpenAPI spec when reading it and understanding it, so I knocked up a simple shell script that takes an OpenAPI spec file and outputs an HTML doc. This is a trivial task thanks to Scalar!
This is the script:
~/bin/create-openapi-spec-doc.sh:
#!/usr/bin/env bash
set -eo pipefail
if [[ $# -eq 0 ]]; then
echo "Usage: $(basename "$0") <spec-file> [spec-file ...]"
echo "Generates an HTML API reference document for each OpenAPI spec file provided."
exit 1
fi
for spec_file in "$@"; do
base="${spec_file%.*}"
spec_name="$(basename "$base")"
{
cat <<EOF
<!doctype html>
<html>
<head>
<title>${spec_name} API</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1" />
</head>
<body>
<div id="app"></div>
<script
id="api-reference"
type="application/yaml">
EOF
cat "$spec_file"
cat <<'EOF'
</script>
<!-- Load the Script -->
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
EOF
} > "$base".html
echo "Generated: $base.html"
done
$ create-openapi-spec-doc.sh *.json
Generated: provided_svc.html
Generated: required_svc.html
and now I have nicely formatted HTML files!


