DEV Community

Koji (he/him)
Koji (he/him)

Posted on

Let's Display The Response From API Beautifully

Probably you have used console.log to display data from API.

import fetch from "node-fetch";

const getDevToData = async() => {
    try {
      const url = "https://dev.to/api/articles";
      const resp = await fetch(url);
      const data = await resp.json();      
      console.log(data[0]); // In this post i just need to check one
    } catch(err) {
        console.log(err);
    }
}

const devData = getDevToData();
Enter fullscreen mode Exit fullscreen mode

Maybe we need to add like the below.

console.log(`id: ${data[0].id}`);
console.log(`title: ${data[0].title}`);
Enter fullscreen mode Exit fullscreen mode

But sometimes we need the entire response which should be readable for us(human). The following small function helps us.

ts

const printObj = (obj:any) => {
  console.log(JSON.stringify(obj, null, 4));
}
Enter fullscreen mode Exit fullscreen mode

js

const printObj = (obj) => {
  console.log(JSON.stringify(obj, null, 4));
}
Enter fullscreen mode Exit fullscreen mode

The screenshot is using Chrome to use TypeScript playground since I'm lazy and don't want to create a project for the following code.
But if you use Nodejs, you will see the difference easily and will like this small function. Actually, this really helps me lol

The number is for indent. I'm using 2 for coding, but still, prefer 4 for JSON.

Alt Text

By the way, I used dev.to API for this post.

dev.to api

https://docs.dev.to/api/#section/Authentication

TypeScript playground

Discussion (0)