Home > Blockchain >  How do I call a different REST API within a express route?
How do I call a different REST API within a express route?

Time:10-21

I have an express.js REST API that I have created with a variety of routes. I'd like to create a route to call another REST API and then return the result. Ideally, it should look something like the following:

router.post('/CreateTicket', cors(corsOptions), function(req, res, next) {
   //make a call to another rest api and then res.send the result
}

The REST API route that I am calling is a POST request and will take in a JSON body with the information for the ticket. It then will return a JSON response containing the ticket information and ticket link.

Essentially, I just want to pass req.body as the body of the API call and then res.send() the response of the API call. I was trying to figure out some way to use fetch or requests, but was just getting confused.

Thank you so much for any help that anyone can offer!

CodePudding user response:

I would suggest to use axios if you want to call the third-party API. The simple way of doing is to create an options(config) pass it to the axios object.

npm i axios --save 

Axios config

  const options = {
    'method': 'POST',
    'url': 'https://URL',
    'headers': {
      'Content-Type': 'application/json'
    },
    data: {
       firstName: 'Fred',
       lastName: 'Flintstone'
    }
  };

  try {
    const result = await axios(options);
    console.log(result);
  } catch (e) {
       console.log(e);
  }
  

In your route file:

const axios = require('axios');


const getData = async (body) => {
      const options = {
    'method': 'POST',
    'url': 'https://URL',
    'headers': {
      'Content-Type': 'application/json'
    },
    data: {
      body
    }
  };

  try {
    const result = await axios(options);
    console.log(result);
    return result;
  } catch (e) {
       console.log(e);
  }
}

router.post('/CreateTicket', cors(corsOptions), async function(req, res, next) {
   //make a call to another rest api and then res.send the result
  try {
    const response = await getData(req.body);
   res.send(response);
  } catch (e) {
    //wrap your error object and send it
  }
   
}

Note: if you want to pass the data to your own created route you can use res.redirect and it will send the response back. You can check the axios details in the link above.

CodePudding user response:

You would have to use something like axios or http (code originates from link):

const https = require('https')
const options = {
  hostname: 'example.com',
  port: 443,
  path: '/todos',
  method: 'GET'
}

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', d => {
    return d
  })
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related