Home > Blockchain >  How to call an api in express? [closed]
How to call an api in express? [closed]

Time:09-17

NodeJS Task -

Create one server using expressjs. And then call this public free API - https://api.coindesk.com/v1/bpi/currentprice.json And then get the list of prices from that Api and send the prices in rupees as a response. Use postman to call your created API endpoint e.g. localhost:3000/api/prices and you should get the response in json format as given below. [‘1.00’, ‘2.00’, ‘3.00’]

Above is the task I got and I know only about server creation. I need to know how to call an API from that server.

CodePudding user response:

Just use axios. https://www.npmjs.com/package/axios

const axios = require('axios');

...


axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(res => {
   console.log(res.data)
}).catch(err => console.log(err));

CodePudding user response:

Just use fetch. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

 fetch('https://api.coindesk.com/v1/bpi/currentprice.json').then(res => 
     res.json())
     .then((res) => console.log(res))
     .catch(err => console.log(err));

CodePudding user response:

const axios = require('axios');

async function getData() {
  const {data} = await axios.get("https://api.coindesk.com/v1/bpi/currentprice.json")

// do what ever you want
}

CodePudding user response:

I will recommend you to use the Promise and request module to get data from the third part apis. Below is the working code snippet that will be helpful for you to get data. Integrate this code with your node server.

    const request = require("request");
    function getPrices(){
      return new Promise((resolve, reject)=> {
        let options = {
         method: "GET",
         url: "https://api.coindesk.com/v1/bpi/currentprice.json",
         json: true
        }
        request(options, (error, response, body) => {
          if (!error && response.statusCode === 200) {
           resolve(body);        
          }
          reject(error);
        });
      });
    }
    
    getPrices().then(data =>{ 
      console.log(data);
    }).catch(error=>{
      console.log(error);
    });

  • Related