Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API GET request from my api to another api?

I'm trying to create a backend that sends a GET request to another API.

For example:

My API: localhost:3000/
Route: /getdata/data1
Other API: api.com/target/data

(This is a fake URL, just assume that this route has the data that I want)

How can I send a get request to that API from my API? Ajax.get?

like image 713
Ext- Avatar asked Sep 09 '26 16:09

Ext-


1 Answers

You can use the built-in http module in node, or use a third-party package such as request.

HTTP

An example of using the built in http module e.g:

// The 'https' module can also be used
const http = require('http');

// Example route
app.get('/some/api/endpoint',  (req, res) => {

    http.get('http://someapi.com/api/endpoint', (resp) => {
        let data = '';

        // Concatinate each chunk of data
        resp.on('data', (chunk) => {
          data += chunk;
        });

        // Once the response has finished, do something with the result
        resp.on('end', () => {
          res.json(JSON.parse(data));
        });

        // If an error occured, return the error to the user
      }).on("error", (err) => {
        res.json("Error: " + err.message);
      });
});

Request

Alternatively, a third party package such as request can be used.

First install request:

npm install -s request

And then change your route to something like this:

const request = require('request');

// Example route
app.get('/some/api/endpoint',  (req, res) => {

    request('http://someapi.com/api/endpoint',  (error, response, body) => {
        if(error) {
            // If there is an error, tell the user 
            res.send('An erorr occured')
        }
        // Otherwise do something with the API data and send a response
        else {
            res.send(body)
        }
    });
});
like image 75
Ash Avatar answered Sep 12 '26 16:09

Ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!