Using @karhoo/demand-api package

Web Demand API is library that provides the ability to contact Karhoo's public API and allows you to send and receive network calls and responses.

Installation

npm i @karhoo/demand-api

Warnings

This library uses Promise and fetch. For old browsers, e.g. IE11 you must bring your own polyfill. You can use js-core@3 to polyfill Promise and isomorphic-fetch to polyfill `fetch

Http service

const {
  HttpService,
  LocationService,
  PoiService,
  QuotesService,
} = require('@karhoo/demand-api')

const httpService = new HttpService(
  'https://rest.sandbox.karhoo.com/v1'
).setDefaultRequestOptionsGetter(() => ({
  headers: {
    Authorization: '<you token>',
  },
}))

LocationService

constructor

Parameters

http: Http

Returns: void

getAddressDetails

Parameters

details: LocationAddressDetailsParameters

Returns: Promise<LocationAddressDetailsResponse>

getAddressAutocompleteData

data: LocationAddressAutocompleteParams

Returns: Promise<LocationAddressAutocompleteResponse>

ParamTypeRequired
placeIdstring*
sessionTokenstring

ParamTypeRequired
querystring*
position{ latitude, longitude }
radiusnumber
sessionTokenstring*

Example

const locationService = new LocationService(httpService)

// Get the trip origin’s Place ID
const originAutocompleteResults = await locationService.getAddressAutocompleteData({
  query: 'Paddington, London, UK', 
  sessionToken: 'f36e41a4-951d-11ea-bb37-0242ac130002'
})

// Get the destination’s Place ID
const destinationAutocompleteResults = await locationService.getAddressAutocompleteData({
  query: 'London Eye',
  sessionToken: '2fc547a6-951e-11ea-bb37-0242ac130002'
})

// Next steps needed for displaying nice addresses on UI

// Get origin's location details 
const originPlaceId = await locationService.getAddressDetails({
   placeId: originAutocompleteResults.locations[0].placeId,
   sessionToken: 'f36e41a4-951d-11ea-bb37-0242ac130002'
})

// Get destinations's location details
const destinationPlaceId = await locationService.getAddressDetails({
   placeId: destinationAutocompleteResults.locations[0].placeId,
   sessionToken: '2fc547a6-951e-11ea-bb37-0242ac130002'
})

PoiService

constructor

Parameters

http: Http

Returns: void

search

Parameters

params: PoiSearchParams

Returns: Promise<PoiSearchResponse>

ParamTypeRequired
searchTermstring
searchKeystring
paginationRowCountnumber*
paginationOffsetnumber*

Example

const poiService = new PoiService(httpService)

// gets only one possible item
const response = await poiService.search({
  searchKey: 'FRTM',
  paginationRowCount: 1,
  paginationOffset: 1,
})

QuotesService

constructor

Parameters

http: Http

Returns: void

checkAvailability

Parameters

params: QuotesAvailabilityParams

Returns: Promise<QuotesAvailabilityResponse>

quotesSearch

Parameters

params: QutesSearchParams

Returns: Promise<QuotesResponse>

quotesSearchById

Parameters

id: string

Returns: Promise<QuotesByIdResponse>

ParamTypeRequired
originPlaceIdstring*
destinationPlaceIdstring
dateRequiredstring

ParamTypeRequired
origin_place_idstring*
destination_place_idstring*
local_time_of_pickupstring

Example

const quotesService = new QuotesService(httpService)

// check if quotes available at the specified location
const availability = await quotesService.checkAvailability({
  originPlaceId: "k_005f8ca4-eb41-11e9-8162-969c8418bcef" 
})

// get list of quotes
const quotesSearchResponse = await quotesService.quotesSearch({
  origin_place_id: "k_005f8ca4-eb41-11e9-8162-969c8418bcef",
  destination_place_id: "ChIJ2dGMjMMEdkgRqVqkuXQkj7c",
  local_time_of_pickup: "2020-05-19T12:00"
})

// get list of quotes for a given id
const quotesByIdResponse = await quotesService.quotesSearchById("1234567")

//polling quotes by id
async function requestQuotesById(id, intervalIndex = 0) {
	const pollIntervals = [2000, 1000, 2000]
	const sleepTime = pollIntervals[intervalIndex] || 5000

	const response = await quotesServise.quotesSearchById(id)

	if(response.ok) {
		const status = await response.body.status
 		if (status === "PROGRESSING") {
    	await new Promise(res => {
      	setTimeout(()=> {resolve()},sleepTime)
      }) 	
    	
      return requestQuotesById(id, intervalIndex + 1)
  	} else {
    	// handle completed quotes
  	}
	} else {
  	// handle error response
	}
}

TripService

constructor

Parameters

http: Http

Returns: void

trackTrip

Parameters

id: string

Returns: Promise<TripFollowResponse>

book

Parameters

params: BookATripParams

Returns: Promise<https://github.com/karhoo/web-lib-demand/blob/master/packages/demand-api/src/trip/types.ts#L123)\>

cancel

Parameters

id:string

params: CancellationParams

Returns: either success (void) or an Error

cancelByFollowCode

Parameters

id:string

params: CancellationParams

Returns: either success (void) or an Error

search

Parameters

params: SearchParams

Returns: Promise<SearchResponse>

bookWithoutNonce

Parameters

params: BookATripWithoutNonceParams

Returns: Promise<BookATripResponse>

getBookingDetails

Parameters

id: string

Returns: Promise<BookATripResponse>

getTripStatus

Parameters

id: string

Returns: Promise<GetTripStatusResponse>

getTripPosition

Parameters

id: string

Returns: Promise<GetTripPositionResponse>

ParamTypeRequired
metaobject
quote_idstring*
passengersPassengers*
partner_trip_idstring
flight_numberstring
train_numberstring
cost_center_referencestring
payment_noncestring*
train_timestring
loyalty_programmestring
loyalty_pointsnumber

ParamTypeRequired
quote_idstring*
passengersPassengers*
metaobject
partner_trip_idstring
commentsstring
flight_numberstring
train_numberstring
cost_center_referencestring
train_timestring

ParamTypeRequired
additional_passengersnumber
luggage{ total }
passenger_details[ PassengerDetails ]*

ParamTypeRequired
first_namestring
last_namestring*
emailstring
phone_numberstring*
localestring

ParamTypeRequired
reasonstring*
explanationstring

ParamTypeRequired
trip_states[TripStatus]
trip_type"BOTH" | "PREBOOK" | "ASAP"
created_afterstring
emailstring
traveller_idstring
prebook_time_afterstring
prebook_time_beforestring
trip_time_beforestring
trip_time_afterstring
only_without_final_priceboolean
pagination_offsetnumber
pagination_row_countnumber
fleet_idstring
partner_trip_idstring
external_trip_idstring
forenamestring
lastnamestring
display_trip_idstring
order_by[string]

| 'REQUESTED'
| 'COMPLETED'
| 'DRIVER_EN_ROUTE'
| 'CONFIRMED'
| 'ARRIVED'
| 'POB'
| 'DRIVER_CANCELLED'
| 'BOOKER_CANCELLED'
| 'NO_DRIVERS_AVAILABLE'
| 'KARHOO_CANCELLED'
| 'FAILED'
| 'PREAUTH_DECLINED'
| 'INCOMPLETE'

Example

const tripService = new TripService(httpService)

// get trip information for specified tripID
const tripResponse = await tripService.trackTrip("47eda69d-776d-45b6-b12c-5b5fe4f6d447")

// book a trip
const bookATripResponse = await tripService.book({
  quote_id: "47eda69d-776d-45b6-b12c-5b5fe4f6d447",
  payment_nonce: "939b47f1-59fb-0ff9-7917-04d21ab8faab",
  passengers: {
    additional_passengers: 0,
    luggage: {
      total: 0
    },
    passenger_details:[{
      email: "[email protected]",
      first_name: "Jon",
      last_name: "Doe",
      locale: "en_GB",
      phone_number: "+3892562156563"
    }]
  }  
})

// cancel a trip (the same for cancelByFollowCode)
const cancellationParams= {
  reason: 'Driver is late'
}

const cancelTrip = await tripService.cancel("47eda69d-776d-45b6-b12c-5b5fe4f6d447", cancellationParams)

// search a trips with given statuses
const searchParams = {
  tripStates: ["REQUESTED", "COMPLETED"],
  order_by: "Date"
}

const searchTripsResponse = await tripService.search(searchParams)

// get a trip status
const id = "47eda69d-776d-45b6-b12c-5b5fe4f6d447"
const tripStatus = await tripService.getTripStatus(id)

// get a trip position
const id = "47eda69d-776d-45b6-b12c-5b5fe4f6d447"
const tripPosition = await tripService.getTripPosition(id)

AuthService

constructor

Parameters

http: Http

Returns: void

login

Parameters

params: LoginParams

Returns: Promise<LoginResponse>

refreshToken

Parameters

params:RefreshTokenParams

Returns: Promise<RefreshTokenResponse>

ParamTypeRequired
usernamestring*
passwordstring*

ParamTypeRequired
refresh_tokenstring*

Example

const authService = new AuthService(httpService)

// login
const loginResponse = await authService.login({
  username:'[email protected]',
  password: 'xY2182731jashd!'
}

// refresh token
const refreshTokenResponse = await authService.refreshToken({
  access_token: 'eyJz93a...k4laUWw',
  expires_in: 86400
})

UserService

constructor

Parameters

http: Http

Returns: void

getCurrentUser

Parameters

no parameters needed

Returns: Promise<GetCurrentUserResponse>

resetPassword

Parameters

email: string

Returns: either success (void) or an Error

getOrganisationConfiguration

Parameters

id: string

Returns: Promise<GetOrganisationConfigurationResponse>

Example

const userService = new UserService(httpService)

// get current user information
const getCurrentUserResponse = await userService.getCurrentUser()

// reset password
const resetPassword = await userService.resetPassword({ email: '[email protected]' })

// get organisation configuration by id
const organisationConfigurationResponse = await userService.getOrganisationConfiguration({ id: '123456-abc' })