Automating HackMD documents
- 2 minutes read - 346 wordsI was introduced to HackMD while working on an open-source project. It’s a collaborative editing tool for Markdown documents and there’s an API
I wanted to be able to programmatically edit one of my documents with a daily update. The API is easy-to-use and my only challenge was futzing with escape characters in bash strips representing the document Markdown content.
You’ll need an account with HackMD and an to Create API Token that I’ll refer to as TOKEN
.
TOKEN="[YOUR-TOKEN]"
HackMD’s API documentation suggests getting your (me
) user information to confirm that alles ist in Ordnung:
curl \
--silent \
--header "Authorization: Bearer ${TOKEN}" \
https://api.hackmd.io/v1/me" \
| jq .
NOTE Drop
| jq .
if you don’t want to usejq
You can then enumerate your notes:
curl \
--silent \
--header "Authorization: Bearer ${TOKEN}" \
https://api.hackmd.io/v1/notes \
| jq .
Identify a sacrificial (!) document and grabs its id
. I’ll refer to it as ID
.
ID="[YOUR-DOCUMENT-ID]"
Then you can retrieve the document:
curl \
--silent \
--header "Authorization: Bearer ${TOKEN}" \
https://api.hackmd.io/v1/notes/${ID} \
| jq .
We’re going to manipulate the Markdown content only:
CONTENT=$(\
curl \
--silent \
--header "Authorization: Bearer ${TOKEN}" \
https://api.hackmd.io/v1/notes/${ID} \
| jq .content)
NOTE It is important that you not use
jq -r
You should receive a string containing the Markdown content of your document.
I assume there are bash-based Markdown processing tools (!?) but I used sed
to update my document.
Be careful that the result of your processing (sed
or your preferred tool) does not remove e.g. \n
from your CONTENT
string literal.
When you are confident that the output of your processing remains valid Markdown, you can update (or create a new) document:
curl \
--silent \
--request PATCH \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--data "{\"content\": ${CONTENT}}" \
https://api.hackmd.io/v1/notes/${ID}
NOTE You must include the
Content-Type
header and thedata
string needs to be expanded with the value ofCONTENT
but it is not necessary to double-quote the resulting value because it should (!) have retained these.
Your document should be updated.