Home > other >  How to fetch data from two different API and map them in expressjs
How to fetch data from two different API and map them in expressjs

Time:10-12

I am new to Node Express. I know how to do that in PHP but not able to understand in Express JS.

My problem is, I want to fetch Cars Package from two different API or more and create new response by joining their response.

I am using two different API, one is Talixo and Another is IWay.

here are the sample response from them.

sample response from talixo

{
      "taxis": [],
      "limousines": [
    {
      "luggage": 3,
      "seats": 3,
      "animals": false,
      "wheelchairs": false,
      "sport_luggage": 2,
      "car_model": "Toyota Prius",
      "children_seat_1": "I/II/III: 9 - 36 kg",
      "children_seat_2": "I/II/III: 9 - 36 kg",
      "id": "34427",
      "color": "black",
      "booking_category": "economy",
      "extended_booking_category": "economy",
      "currency_symbol": "€",
      "currency_code": "EUR",
      "talixo_points": 80,
      "vehicle_type": "limo",
      "included_waiting_time": 45,
      "regular_price": 34.65,
      "discount_price": 34.65,
      "local_price": "",
      "frame_contract": "Integrations",
      "tolls_included": true,
      "gratuity_included": true,
      "search_url": "",
      "image_url": "https://static.talixo.de/images/vehicles/economy.png"
    },
    {
      "luggage": 7,
      "seats": 6,
      "animals": false,
      "wheelchairs": false,
      "sport_luggage": 2,
      "car_model": "VW T5",
      "children_seat_1": "I/II/III: 9 - 36 kg",
      "children_seat_2": "I/II/III: 9 - 36 kg",
      "id": "34429",
      "color": "black",
      "booking_category": "economy",
      "extended_booking_category": "economy_van",
      "currency_symbol": "€",
      "currency_code": "EUR",
      "talixo_points": 80,
      "vehicle_type": "limo",
      "included_waiting_time": 45,
      "regular_price": 46.75,
      "discount_price": 46.75,
      "local_price": "",
      "frame_contract": "Integrations",
      "tolls_included": true,
      "gratuity_included": true,
      "search_url": "",
      "image_url": "https://static.talixo.de/images/vehicles/economy_van.png"
    },
     .......
    ]
}

and sample response from iway is here

    {
  "result": [
    {
      "price_uid": "aaecf387-dca1-4070-94e9-03f3a40c394b",
      "price": 59.3,
      "price_rub": 4420,
      "reverse_id": null,
      "reverse_price": {
        "price": 0
      },
      "currency": "EUR",
      "service_id": 1,
      "car_class": {
        "car_class_id": 2,
        "title": "Standard",
        "models": [
          "Volkswagen Jetta",
          "Skoda Octavia",
          "Toyota Previa",
          "Audi A4"
        ],
        "photo": "6b6xw3z2m1.png",
        "capacity": 3
      },
      "allowable_subaddress": 3,
      "price_subaddress": 59.3,
      "price_subaddress_rub": 4420,
      "cancellation_time": 6,
      "type": 2,
      "payed_road": false,
      "blackout_date": [],
      "allowable_time": 6,
      "class_services": [
        {
          "id": 1,
          "title": "Встреча с табличкой",
          "value": "Да"
        },
        {
          "id": 2,
          "title": "Бесплатное ожидание",
          "value": "20"
        },
        {
          "id": 3,
          "title": "Дополнительный заезд (зависит от настроек заказчика)",
          "value": "Да"
        }
      ],
      "id_custom_price": 100003569,
      "additional_services": [
        {
          "id": 7823,
          "additional_service_id": 2,
          "price": 8.92,
          "name": "Детское кресло “от 0 до 1 года”",
          "description": null,
          "uid": "5d3da41a-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.infant_seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "infant_seat",
          "price_rub": 665
        },
        {
          "id": 7829,
          "additional_service_id": 3,
          "price": 7.14,
          "name": "Детское кресло “от 1 до 3 лет”",
          "description": null,
          "uid": "88833caf-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "seat",
          "price_rub": 532
        },
        {
          "id": 7835,
          "additional_service_id": 4,
          "price": 7.14,
          "name": "Детское кресло “от 3  лет”",
          "description": null,
          "uid": "a988554c-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.booster.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "booster",
          "price_rub": 532
        }
      ],
      "additional_services_revert": [
        {
          "id": 7823,
          "additional_service_id": 2,
          "price": 8.92,
          "name": "Детское кресло “от 0 до 1 года”",
          "description": null,
          "uid": "5d3da41a-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.infant_seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "infant_seat"
        },
        {
          "id": 7829,
          "additional_service_id": 3,
          "price": 7.14,
          "name": "Детское кресло “от 1 до 3 лет”",
          "description": null,
          "uid": "88833caf-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "seat"
        },
        {
          "id": 7835,
          "additional_service_id": 4,
          "price": 7.14,
          "name": "Детское кресло “от 3  лет”",
          "description": null,
          "uid": "a988554c-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.booster.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "booster"
        }
      ],
      "is_fast_booking": false,
      "flexible_tariff": false,
      "flexible_tariff_agreement": true,
      "price_id": 3020640,
      "minimum_duration": 0,
      "start_place": {
        "place_id": 7891,
        "title": "Undefined",
        "type": 6,
        "type_title": "Others",
        "terminal": [],
        "declension_titles": {
          "nom": null,
          "gen": null,
          "acc": null
        }
      },
      "finish_place": {
        "place_id": 3372,
        "title": "Dubai (center)",
        "type": 9,
        "type_title": "downtown",
        "terminal": [],
        "declension_titles": {
          "nom": null,
          "gen": null,
          "acc": null
        }
      },
      "additional_service_info": {
        "type_place_start": 6,
        "type_place_finish": 6,
        "start_city_id": 395
      }
    },
    {
      "price_uid": "89d1ea54-38a5-40cf-84fd-ba705e6f31ca",
      "price": 103.77,
      "price_rub": 7734,
      "reverse_id": null,
      "reverse_price": {
        "price": 0
      },
      "currency": "EUR",
      "service_id": 1,
      "car_class": {
        "car_class_id": 6,
        "title": "Minivan",
        "models": [
          "Toyota Previa"
        ],
        "photo": "36eg82060g.png",
        "capacity": 5
      },
      "allowable_subaddress": 3,
      "price_subaddress": 103.77,
      "price_subaddress_rub": 7734,
      "cancellation_time": 12,
      "type": 2,
      "payed_road": false,
      "blackout_date": [],
      "allowable_time": 12,
      "class_services": [
        {
          "id": 1,
          "title": "Встреча с табличкой",
          "value": "Да"
        },
        {
          "id": 2,
          "title": "Бесплатное ожидание",
          "value": "20"
        },
        {
          "id": 3,
          "title": "Дополнительный заезд (зависит от настроек заказчика)",
          "value": "Да"
        }
      ],
      "id_custom_price": 100003571,
      "additional_services": [
        {
          "id": 7820,
          "additional_service_id": 2,
          "price": 8.92,
          "name": "Детское кресло “от 0 до 1 года”",
          "description": null,
          "uid": "51434503-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.infant_seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "infant_seat",
          "price_rub": 665
        },
        {
          "id": 7826,
          "additional_service_id": 3,
          "price": 7.14,
          "name": "Детское кресло “от 1 до 3 лет”",
          "description": null,
          "uid": "7db22146-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "seat",
          "price_rub": 532
        },
        {
          "id": 7832,
          "additional_service_id": 4,
          "price": 7.14,
          "name": "Детское кресло “от 3  лет”",
          "description": null,
          "uid": "9f932316-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.booster.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "booster",
          "price_rub": 532
        }
      ],
      "additional_services_revert": [
        {
          "id": 7820,
          "additional_service_id": 2,
          "price": 8.92,
          "name": "Детское кресло “от 0 до 1 года”",
          "description": null,
          "uid": "51434503-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.infant_seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "infant_seat"
        },
        {
          "id": 7826,
          "additional_service_id": 3,
          "price": 7.14,
          "name": "Детское кресло “от 1 до 3 лет”",
          "description": null,
          "uid": "7db22146-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.seat.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "seat"
        },
        {
          "id": 7832,
          "additional_service_id": 4,
          "price": 7.14,
          "name": "Детское кресло “от 3  лет”",
          "description": null,
          "uid": "9f932316-fe59-11eb-a2d6-e992f37ca87f",
          "slug": "trans.additional_services.booster.name",
          "default_include": false,
          "currency": "EUR",
          "category": "baby_seat",
          "type": "booster"
        }
      ],
      "is_fast_booking": false,
      "flexible_tariff": false,
      "flexible_tariff_agreement": true,
      "price_id": 3020641,
      "minimum_duration": 0,
      "start_place": {
        "place_id": 7891,
        "title": "Undefined",
        "type": 6,
        "type_title": "Others",
        "terminal": [],
        "declension_titles": {
          "nom": null,
          "gen": null,
          "acc": null
        }
      },
      "finish_place": {
        "place_id": 3372,
        "title": "Dubai (center)",
        "type": 9,
        "type_title": "downtown",
        "terminal": [],
        "declension_titles": {
          "nom": null,
          "gen": null,
          "acc": null
        }
      },
      "additional_service_info": {
        "type_place_start": 6,
        "type_place_finish": 6,
        "start_city_id": 395
      }
    }
  ],
  "error": null
}

and i want to create my own response from their data like.

{
                    'activityid': "",
                    'availabletime': "",
                    'carimageurl': "",
                    'freecanceltime': "",
                    'freewaittime': "",
                    'inclusivedesc': "",
                    'hvreferralid': "",
                    'hvreferraltype': "",
                    'maxluggagecount' => "",
                    'maxpassangerscount': "",
                    'originprice': "",
                    'originpriceformatted': "",
                    'packageId': "",
                    'serviceproviderid': "",
                    'serviceprovidername': "Talixo or Iway",
                    'vehicleid': "",
                    'carname': "",
                    'vehicletype': "",
                    'vehicleremarks': "or Similar",
}

this is what i have done so far in express controller

        const httpStatus = require('http-status');
    const pick = require('../utils/pick');
    const catchAsync = require('../utils/catchAsync');
    const axios = require('axios');
    const Talixoapi = 'somekey'
    
    const searchCars = catchAsync(async (req, res) => {
    
        try {
    
            const talixoheaders = {
                'Content-Type': 'application/json',
                'Partner': Talixoapi
            }
    
            const iwayheaders = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
            
            const payload = {
                "start_point": req.body.start_point,
                "end_point": req.body.end_point,
                "start_time_date": req.body.start_time_date,
                "start_time_time": req.body.start_time_time,
                "passengers": req.body.passengers,
                "sport_luggage": req.body.sport_luggage,
                "animals": req.body.animals,
                "luggage": req.body.luggage
            }

//talixo api request

            const { data } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
                headers: talixoheaders
            })

//iway api request    
            const { iwaydata } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=747853&lang=en&currency=EUR&start_place_point=24.9178231,55.0111167&finish_place_point=25.259478,55.3229291`, {
                headers: iwayheaders
            })
            
            res.json(data)
        }
        catch (err) {
    
            res.send(err)
    
        }
    
    });
    
    
    module.exports = {
        searchCars
    }

i don't know what to do next here in controller.

what i understand till now is that, i need to create own json array by using foreach for every results and then merge all the arrays.

one more issue, i don't know why but when i use

const { iwaydata } or const { talixodata }, it gives blank result, but when i use const { data }, it works fine.

and this is what i have done till now by following suggestions from @sangam rajpara.

const searchCars = catchAsync(async (req, res) => {

try {

    const talixoheaders = {
        'Content-Type': 'application/json',
        'Partner': Talixoapi
    }

    const iwayheaders = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ***************'
    }
    
    const payload = {
        "start_point": req.body.start_point,
        "end_point": req.body.end_point,
        "start_time_date": req.body.start_time_date,
        "start_time_time": req.body.start_time_time,
        "passengers": req.body.passengers,
        "sport_luggage": req.body.sport_luggage,
        "animals": req.body.animals,
        "luggage": req.body.luggage
    }

    const { data: talixoData } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
        headers: talixoheaders
    })

    const { data: iwayData } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=1863&lang=en&currency=USD&start_place_point=24.9178231,55.0111167&finish_place_point=25.259478,55.3229291`, {
        headers: iwayheaders
    })

    const taxiresults = [];

    if (talixoData.taxis.length) {
        talixoData.taxis.forEach(function (item) {
            arrcars = {};
            arrcars["carname"] = item.car_model;
            arrcars["originprice"] = item.regular_price;
            arrcars["packageId"] = item.id;
            arrcars["image"] = item.image_url;
            arrcars["vendor"] = "Talixo";
            arrcars["vehicleremarks"] = "Or Similar";
            taxiresults.push(arrcars);
        });
    }
    
    if (talixoData.limousines.length){
        talixoData.limousines.forEach(function (item) {
            arrcars = {};
            arrcars["carname"] = item.car_model;
            arrcars["originprice"] = item.regular_price;
            arrcars["packageId"] = item.id;
            arrcars["image"] = item.image_url;
            arrcars["vendor"] = "Talixo";
            arrcars["vehicleremarks"] = "Or Similar";
            taxiresults.push(arrcars);
        });
    }

    if (iwayData.result.length) {
        iwayData.result.forEach(function (item) {
            var imgsrc = "https://iwayex.com/images/cars/";
            arrcars = {};
            arrcars["carname"] = item.car_class.models[0];
            arrcars["originprice"] = item.price;
            arrcars["packageId"] = item.price_uid;
            arrcars["image"] = imgsrc   item.car_class.photo;
            arrcars["vendor"] = "iway Transfers";
            arrcars["vehicleremarks"] = "Or Similar";
            taxiresults.push(arrcars);
        });
    }
   
    res.json(taxiresults)
}
catch (err) {

    res.send(err)

}

});

CodePudding user response:

As per Axios, you receive API response data in the data key of the response object.

What you can do is.

//talixo api request

        const { data: talixoData } = await axios.post(`https://talixo.com/en/mapi/v3/vehicles/booking_query/`, payload, {
            headers: talixoheaders
        })

//iway api request    
        const { data: iwayData } = await axios.get(`https://sandbox.iway.io/transnextgen/v3/prices?user_id=747853&lang=en&currency=EUR&start_place_point=24.9178231,55.0111167&finish_place_point=25.259478,55.3229291`, {
            headers: iwayheaders
        })

If you are new to javascript what I did is destructured the object and renamed key data.

  • Related