DEV Community

Cover image for How to get Dev Comments from an article Url
Waylon Walker
Waylon Walker

Posted on • Originally published at on

How to get Dev Comments from an article Url

I want to incorporate some of the wonderful comments, 💕, 🦄, and 🔖's that I have been getting on on my website. I have dabbled once or twice with no avail this time I am taking notes on my journey, so follow along and let's get there together. By the end of this post, I will have a way to get comments from posts on the client-side thanks to the wonderfully open API.

The Comments API has an open API that allows us to easily get comments as HTML. They have their API hosted at, let's take a look at it.

Here we can see that going to returns us some json, that contains an array of comments that look something like this.

  {body_html: '<the comment rendered as html>',
   user: {<an array with quite a bit of information about the commenting user>},
   children: [<an array of child comment objects>]
   <other stuff we dont care about>
  <more comments>
Enter fullscreen mode Exit fullscreen mode

What the heck is that a_id 🤔

That is an article_id. Though a bit of searching I found that it occurs in at least four places on every page as a data attribute. Using chrome dev tools I found a good place to "query" it from.

With this knowledge, we can fetch the contents of an article and pull the articleId from it.

    async function getDevToAId(url) {
        // Gets the articleId of a article
        const root = ''
        if (!url.includes(root)) {
            url = root + url
        let domparser = new DOMParser()
        const html = await fetch(url).then(r => r.text())
        const doc = domparser.parseFromString(html, 'text/html')
        const articleId = doc.querySelector('#article-body').dataset.articleId
        return articleId
Enter fullscreen mode Exit fullscreen mode

note I do check to see if a full URL or slug was given, if it was just the slug I tack on before fetching.

Now the comments ✨

The main event is here, what you all have waited for, and it's by far the easiest part.

    async function getDevToComments(url) {
        const articleId = await getDevToAId(url)
        const response = await fetch(`${articleId}`)
        const comments = await response.json()
        return comments
Enter fullscreen mode Exit fullscreen mode

The hardest part of this was figuring out what the a_id was and how I was going to get it from some more commonly known information about my articles, the URL, or the slug

Try it out 💻

F12 pop open your console right in dev tools of this post and try it out.

Top comments (0)