DEV Community

mafflerbach
mafflerbach

Posted on

Publish new posts via API on dev.to

So, this is it. My first article on dev.to. As you may guess, because of the title this article didn't use the web interface for publishing.

I wanted to use the dev.to API. At this point i have to admit, that i am a vim junkie and also love to automate stuff and like to write small nifty scripts which are handle anoying tasks which i have to do more than three or more times.

I am also avoiding web interfaces if possible and prefer a cli over a gui. Therefore it is naturally for me to think about how to write and publish new posts in a seamless way from vim.

On the first glance, the API Documentation from dev.to seem simple and well documented.
The first steps shows how to create an API key, and all endpoints have examples for requests, responses and, what exited me the most, curl snippets.

My first target is, to publish a new post. So i took a closer look on the create endpoint. The request is build up like this:

{
  "article": {
    "title": "Hello, World!",
    "published": true,
    "body_markdown": "Hello DEV, this is my first post",
    "tags": [
      "discuss",
      "help"
    ],
    "series": "Hello series",
    "canonical_url": "https://example.com/blog/hello"
  }
}
Enter fullscreen mode Exit fullscreen mode

Very simple. I decided to write a small bash script which will post my new Post to dev.to.

To publish a new article we just use this example as base:

curl -X POST -H "Content-Type: application/json" \
  -H "api-key: API_KEY" \
  -d '{"article":{"title":"Title","body_markdown":"Body","published":false,"tags":["discuss", "javascript"]}}' \
  https://dev.to/api/articles
Enter fullscreen mode Exit fullscreen mode

With a little bit of fiddling and testing i come up with a small, but not foolproove bash script:

#!/bin/bash

# hold my api keys
source ~/dotfiles/.credencials

# for better readability
title=$1
tags=$3
# the content has to be json encoded 
content=$(cat "$2" | jq '.' --raw-input --slurp)

# write it to a tmp file for better debugging and also for using a file path in the curl call
tee /tmp/devtoArticle.md << END
{"article":{"title":"$title","body_markdown":$content,"published":false,"tags":[$tags]}}
END

curl -X POST -H "Content-Type: application/json" \
    -H "api-key: ${devtoApiToken}" \
    -d @/tmp/devtoArticle.md \
    https://dev.to/api/articles
Enter fullscreen mode Exit fullscreen mode

In my opinion, this is just a good enough example, and will be evolve over the time.

The call is like this:

./helper.sh 'Publish new posts via API on dev.to' 'content/Create a new post via API.md' '"bash", "vim", "automation","api"'

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
njfamirm profile image
S. Amir Mohammad Najafi