Amadeus Node SDK

repository·master·Indexed 42 days ago

https://github.com/amadeus4dev/amadeus-node

A promise-based Node.js client library for interacting with Amadeus travel industry APIs. Version 11.1.0 provides structured interfaces for searching and booking flights, hotels, and transfers, accessing reference data for locations and airlines, and utilizing machine learning predictions for trip purpose and flight delays.

Tokens
7.3K
Snippets
29
Records
32
Agent score
53%

What's inside Amadeus

  1. Navigate paginated API results

    master

    If an endpoint supports pagination, the SDK provides .next(), .previous(), .last(), and .first() methods to access subsequent or previous pages. You pass the current response object into these methods. If no page is available, the promise resolves to null.

    amadeus.referenceData.locations.get({
      keyword: 'LON',
      subType: 'AIRPORT,CITY'
    }).then(function(response){
      console.log(response.data); // first page
      return amadeus.next(response);
    }).then(function(nextResponse){
      if (nextResponse) {
        console.log(nextResponse.data); // second page
      }
    });
  2. Initialize the Amadeus client

    master

    You can initialize the Amadeus client in three ways:

    1. Explicitly: Pass clientId and clientSecret in the configuration object.
    2. Environment Variables: If AMADEUS_CLIENT_ID and AMADEUS_CLIENT_SECRET are set in your environment, you can initialize without arguments.
    3. Environment Selection: By default, the SDK uses the test environment. To use the production (pay-as-you-go) environment, set the hostname to 'production'.

    You can also provide a custom logger and set the logLevel (silent, warn, or debug) during initialization.

    const Amadeus = require('amadeus');
    
    // Initialize with credentials and production hostname
    const amadeus = new Amadeus({
      clientId: 'REPLACE_BY_YOUR_API_KEY',
      clientSecret: 'REPLACE_BY_YOUR_API_SECRET',
      hostname: 'production',
      logLevel: 'debug'
    });
  3. Configure logging and debugging

    master

    You can customize logging by providing a logger instance (compatible with the default console) or by setting the logLevel during initialization. Alternatively, use the AMADEUS_LOG_LEVEL environment variable.

    Available logLevel options:

    • silent (default)
    • warn
    • debug
    const amadeus = new Amadeus({
      clientId: 'REPLACE_BY_YOUR_API_KEY',
      clientSecret: 'REPLACE_BY_YOUR_API_SECRET',
      logLevel: 'debug'
    });
  4. How the Client manages authentication and requests

    master

    The Client acts as a wrapper that automates the lifecycle of an API call. When a request is made (e.g., via .get() or .post()):

    1. Authentication: The client uses an internal AccessToken mechanism to retrieve a Bearer Token.
    2. Request Building: It constructs a Request object containing the verb, path, parameters, and connection details (host, port, SSL, etc.).
    3. Execution: It uses the configured http client to execute the request.
    4. Lifecycle Management: It uses an EventEmitter and a Listener to handle the asynchronous response or error, wrapping the entire process in a Promise that resolves with the response or rejects with a ResponseError.

    Note: You can use amadeus.client.get(...) directly, but it is semantically equivalent to using the namespaced API: amadeus.amadeus.reference_data.urls.checkin_links.get(...).

  5. Book a flight order

    master

    Once you have priced a flight offer, you can create a flight order using amadeus.booking.flightOrders.post. This requires the priced offers and traveler information.

    amadeus.booking.flightOrders.post(
      {
        'type': 'flight-order',
        'flightOffers': [priced-offers],
        'travelers': []
      }
    );
  6. Manage transfers

    master

    The SDK supports searching for, booking, and managing ground transfers.

    • Search: amadeus.shopping.transferOffers.post(body).
    • Book: amadeus.ordering.transferOrders.post(body, { offerId: '...' }).
    • Cancel: amadeus.ordering.transferOrder('ORDER_ID').transfers.cancellation.post({}, { confirmNbr: '...' }).
    // Book a transfer
    amadeus.ordering.transferOrders.post(body, { offerId: '2094123123' });
    
    // Cancel a transfer
    amadeus.ordering.transferOrder('XXX').transfers.cancellation.post({}, { confirmNbr: '12345' });
  7. Retrieve flight seat maps

    master

    Seat maps can be retrieved in two ways:

    1. From a flight offer: Pass the flight offer data to amadeus.shopping.seatmaps.post(body).
    2. From a flight order: Use the order ID with amadeus.shopping.seatmaps.get({ 'flight-orderId': 'XXX' }).
    // From flight offers
    amadeus.shopping.flightOffersSearch.get({
      originLocationCode: 'SYD',
      destinationLocationCode: 'BKK',
      departureDate: '2022-11-01',
      adults: '1'
    }).then(function(response){
        return amadeus.shopping.seatmaps.post({
          'data': [response.data[0]]
        });
    }).then(function(response){
        console.log(response.data);
    });
    
    // From a flight order ID
    amadeus.shopping.seatmaps.get({
      'flight-orderId': 'XXX'
    });
  8. Search for hotels and book stays

    master

    Hotel workflows involve searching for offers and then booking them.

    • Search by ID: amadeus.shopping.hotelOffersSearch.get({ hotelIds, adults }).
    • Check Offer Conditions: amadeus.shopping.hotelOfferSearch('ID').get().
    • Booking (v2): amadeus.booking.hotelOrders.post(body).
    • Booking (v1): amadeus.booking.hotelBookings.post(body).

    Hotel lists can also be retrieved by city code (amadeus.referenceData.locations.hotels.byCity.get), geocode, or specific hotel IDs.

    // Search available offers in specific hotels
    amadeus.shopping.hotelOffersSearch.get({
        hotelIds: 'RTPAR001',
        adults: '2'
    })
    
    // Hotel Booking API v2
    amadeus.booking.hotelOrders.post(
      {
        'data': {
            'type': 'hotel-order',
            'guests': [],
            'travelAgent': {},
            'roomAssociations': [],
            'payment': {}
        }
      }
    )
  9. Use Machine Learning predictions

    master

    The SDK includes several predictive APIs to enhance user experience:

    • Trip Purpose: Predict if a trip is Business or Leisure using amadeus.travel.predictions.tripPurpose.get().
    • Flight Delay: Predict flight delays using amadeus.travel.predictions.flightDelay.get() (requires carrier, flight number, aircraft code, etc.).
    • Flight Choice Prediction: Predict user preferences using amadeus.shopping.flightOffers.prediction.post(response) based on search results.
    • On-time Performance: Get airport performance via amadeus.airport.predictions.onTime.get().
    // Flight Delay Prediction
    amadeus.travel.predictions.flightDelay.get({
      originLocationCode: 'BRU',
      destinationLocationCode: 'FRA',
      departureDate: '2020-01-14',
      departureTime: '11:05:00',
      arrivalDate: '2020-01-14',
      arrivalTime: '12:10:00',
      aircraftCode: '32A',
      carrierCode: 'LH',
      flightNumber: '1009',
      duration: 'PT1H05M'
    })
  10. Search for flight offers and price them

    master

    To find flights and then obtain a specific price for an offer, you typically chain a flightOffersSearch.get call with a flightOffers.pricing.post call. The pricing call requires the data from the initial search response.

    You can also include additional parameters in the pricing request, such as checking for baggage options using the include option.

    amadeus.shopping.flightOffersSearch.get({
        originLocationCode: 'SYD',
        destinationLocationCode: 'BKK',
        departureDate: '2022-11-01',
        adults: '1'
    }).then(function(response){
        return amadeus.shopping.flightOffers.pricing.post(
          {
            'data': {
              'type': 'flight-offers-pricing',
              'flightOffers': [response.data[0]]
            }
          }
        )
    }).then(function(response){
        console.log(response.data);
    }).catch(function(responseError){
        console.log(responseError);
    });
    
    // With additional parameters (e.g., baggage)
    amadeus.shopping.flightOffers.pricing.post(body, {include: 'bags'});
  11. Manage flight orders (Retrieve and Cancel)

    master

    You can manage existing flight orders using their unique ID. Note that in the test environment, these IDs are temporary.

    • Retrieve: Use amadeus.booking.flightOrder('ID').get().
    • Cancel: Use amadeus.booking.flightOrder('ID').delete().
    // Retrieve flight order
    amadeus.booking.flightOrder('XXX').get()
    
    // Cancel flight order
    amadeus.booking.flightOrder('XXX').delete()