GitHub: render GitHub-Flavored Markdown with the API

GitHub-Flavored Markdown (GFM) is GitHub’s variant of Markdown, with extra features like task lists and alert boxes. It’s used in issues, pull requests, comments, and many other places on GitHub.
If you’re writing a tool that needs to render GFM, you might try to use a Markdown library, but it’s unlikely to render identically to GitHub. A more accurate alternative is to use GitHub’s REST API endpoint for rendering GFM. It takes a Markdown document and returns the HTML that GitHub would render.
An easy way to try this out is with gh api, the GitHub CLI’s command for using the GitHub REST and GraphQL APIs. For a quick example, say you save this content in a file called example.md:
Oh, what a day! **WHAT A LOVELY DAY!**
You could render it like so:
$ gh api markdown -F mode=gfm -F text=@example.md
<p>Oh, what a day! <strong>WHAT A LOVELY DAY!</strong></p>
Note:
markdownrefers to the/markdownendpoint.-F mode=gfmspecifies that the input is GFM, as opposed to plain Markdown.-F text=@example.mdmakesghpopulate thetextfield with the contents of the fileexample.md.
Add -F context={owner}/{repo} to specify a repository to resolve relative links and references within.
For long-lived code, you should include the Accept and X-GitHub-Api-Version headers, as shown within the documentation. This will ensure that your code continues to work even if GitHub changes the API in the future.
To render content with similar styling to GitHub, use the github-markdown-css project, which provides a CSS file with Markdown-specific rules extracted from GitHub’s CSS.
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
Tags: github