Home > OS >  How to Fetch data from api and insert it inside a new JSON object
How to Fetch data from api and insert it inside a new JSON object

Time:08-01

I am trying to fetch data from an existing api endpoint and using part of that data to create a new endpoint using nodejs and express, in this case I am trying to get the userId from https://jsonplaceholder.typicode.com/posts/1 and inserting it into my new object. I am relatively new to this and it appears I am missing something in my approach to solving this problem. I am hoping someone could point me in the right direction. Below is my desired result

{
"userId": "1",
"another": "yam",
"isLearning": true,
"level": "apprentice"
}

Below is my code so far:

app.get('/contacts', (req, res) => {
    const fetch = require('node-fetch');



    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(jsonData => jsonData.json())
        .then(data => printInfo(data))

    let printInfo = (data) => {
        
        console.log(data.userId)
    }

    const user = {
        userId: data.userId,
        another: "yam",
        isLearning: true, 
        level: 'apprentice'
    };
    return res.json(user);
})

CodePudding user response:

const fetch = require('node-fetch');

app.get('/contacts', (req, res) => {

    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(data=> data.json())
        .then(data => {
            const user = {
                userId: data.userId,
                another: "yam",
                isLearning: true, 
                level: 'apprentice'
            };
            return res.json(user);
        })
})

This approach would be more elegant. We use fetch to fetch data from the API endpoint. It then uses the .then() method to parse the data into JSON format and store it in the variable data. Finally, it creates a new object using data from the API endpoint and returns it as JSON data.

Edit: As pointed out by @danh, this works the formation of the user object must happen after the api request completes (because it depends on data from the request).In the OP code, the formation of the object is attempted before the API completes, even though the code appears "later" in the source.

CodePudding user response:

const fetch = require('node-fetch');

app.get('/contacts', (req, res) => {

    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(data=> data.json())
        .then(data => {
            const user = {
                userId: data.userId,
                another: "yam",
                isLearning: true, 
                level: 'apprentice'
            };
            return res.json(user);
        })
})
  • Related