Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);
})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading