### Development Setup Configuration Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Configure the Duffel client for a development environment. This example shows how to set a fallback token and enable verbose debugging based on the NODE_ENV. ```typescript const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN || 'pk_test_', debug: { verbose: process.env.NODE_ENV === 'development' }, source: `my-app/dev` }) ``` -------------------------------- ### Manual Pagination Example Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/00-index.md Demonstrates how to fetch data in pages using manual pagination parameters like 'limit', 'before', and 'after'. Use 'after' from the previous response to get the next page. ```typescript // Manual const page1 = await duffel.orders.list({ limit: 50 }) const page2 = await duffel.orders.list({ limit: 50, after: page1.meta?.after }) ``` -------------------------------- ### Install Duffel API JavaScript Client Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/00-index.md Install the Duffel API JavaScript client using npm or yarn. ```bash npm install @duffel/api # or yarn add @duffel/api ``` -------------------------------- ### Install Dependencies Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/CONTRIBUTING.md Installs project dependencies using Yarn. This should be run after cloning the repository. ```bash yarn ``` -------------------------------- ### Stays Resource Examples Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md Demonstrates common operations within the 'stays' resource, including searching for hotels, getting accommodation details, and creating bookings from quotes. ```typescript // Search for hotels const search = await duffel.stays.search({ check_in_date: '2024-12-20', check_out_date: '2024-12-25', location: 'London', rooms: [{ adults: 2 }] }) // Get details of a specific accommodation const acc = await duffel.stays.accommodation.get('acc_123') // Create a booking from a quote const booking = await duffel.stays.bookings.create({ quote_id: 'quo_123', guest_email: 'guest@example.com' }) ``` -------------------------------- ### Install Yarn Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/CONTRIBUTING.md Installs Yarn globally if not already present. Ensure you have the correct Node.js version installed. ```bash npm install --global yarn ``` -------------------------------- ### Cars Resource Examples Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md Provides examples for the 'cars' resource, including searching for car rentals and creating bookings from quotes. ```typescript // Search for cars const search = await duffel.cars.search({ pick_up_location: 'LHR', pick_up_date: '2024-12-20', pick_up_time: '10:00', drop_off_date: '2024-12-25', drop_off_time: '18:00' }) // Create a booking const booking = await duffel.cars.bookings.create({ quote_id: 'quo_123', renter_email: 'renter@example.com' }) ``` -------------------------------- ### Bootstrap Next.js with Duffel Example Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/examples/with-next/README.md Use these commands to initialize a new project using the official Duffel Next.js starter template. ```bash npx create-next-app duffel-next-starter --example "https://github.com/duffelhq/duffel-api-javascript/tree/main/examples/with-next" # or yarn create next-app duffel-next-starter --example "https://github.com/duffelhq/duffel-api-javascript/tree/main/examples/with-next" ``` -------------------------------- ### Run in Development Mode Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/CONTRIBUTING.md Starts the project in development mode, enabling hot-reloading and other development-specific features. Check package.json for additional scripts. ```bash yarn dev ``` -------------------------------- ### Duffel API JavaScript Quick Example Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/00-START-HERE.md This snippet shows how to initialize the Duffel client, search for flights, list available offers, and create a booking. Ensure your DUFFEL_ACCESS_TOKEN is set as an environment variable. ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN }) // Search for flights const search = await duffel.offerRequests.create({ slices: [{ origin: 'LHR', destination: 'JFK', departure_date: '2024-12-25' }], passengers: [{ type: 'adult' }] }) // Get offers const offers = await duffel.offers.list({ offer_request_id: search.data.id }) // Book a flight const order = await duffel.orders.create({ offer_id: offers.data[0].id, passengers: [{ id: offers.data[0].passengers[0].id, title: 'mr', given_name: 'John', family_name: 'Doe', gender: 'm', born_on: '1990-01-01', email: 'john@example.com', phone_number: '+442071838750' }], type: 'balance' }) console.log(`Booked: ${order.data.id}`) ``` -------------------------------- ### Multi-Tenant Setup with Client Management Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Implement a multi-tenant architecture by managing multiple Duffel client instances. This pattern ensures that each tenant has its own isolated client, configured with tenant-specific tokens and sources. ```typescript class TravelAPI { private duffelClients: Map = new Map() getDuffel(tenantId: string): Duffel { if (!this.duffelClients.has(tenantId)) { const token = getTokenForTenant(tenantId) this.duffelClients.set(tenantId, new Duffel({ token, source: `tenant/${tenantId}` })) } return this.duffelClients.get(tenantId)! } } ``` -------------------------------- ### Suggestions.list() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Get suggestions for places (cities and airports) matching a query. ```APIDOC ## Suggestions.list() ### Description Get suggestions for places (cities and airports) matching a query. ### Method GET ### Endpoint /places/suggestions ### Parameters #### Query Parameters - **params.query** (string) - Required - Search query (airport code or city name) - **params.locale** (string) - Optional - Language locale (e.g., 'en-US') ### Response #### Success Response (200) - **data** (Place[]) - Array of matching places ### Request Example ```javascript const suggestions = await duffel.suggestions.list({ query: 'london' }) console.log(suggestions.data[0].type) // 'city' or 'airport' console.log(suggestions.data[0].name) ``` ``` -------------------------------- ### Initialize Duffel Client Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/01-client-initialization.md Instantiate the Duffel client with your API token and optional debug settings. Ensure your API token is securely stored, for example, in environment variables. ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN, debug: { verbose: true } }) // Access resources via properties const aircraft = await duffel.aircraft.get('arc_00009VMF8AhXSSRnQDI6Hi') ``` -------------------------------- ### Production Setup Configuration Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Configure the Duffel client for a production environment. This includes setting the API version and dynamically setting the source with your application's version. ```typescript const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN, apiVersion: 'v2', source: `my-app/${process.env.npm_package_version}` }) ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve an offer request by its ID. This method allows fetching a specific offer request using its unique identifier. ```APIDOC ## get(id: string) ### Description Retrieve an offer request by its ID. ### Method GET (assumed based on typical RESTful patterns for retrieval) ### Endpoint /offer_requests/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - Duffel's unique identifier for the offer request ### Response #### Success Response (200) - **data** (OfferRequest) - The offer request object ### Request Example ```javascript const offerRequest = await duffel.offerRequests.get('orq_00009hthhsUZ8W4LxQgkjo') console.log(offerRequest.data.id) ``` ``` -------------------------------- ### Example Error Response Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/README.md The expected JSON structure returned when an API request fails. ```json { "meta": { "status": 404, "request_id": "Fn6SwqLT_Isf3CAAAEah" }, "errors": [ { "type": "invalid_request_error", "title": "Not found", "message": "The resource you are trying to access does not exist.", "documentation_url": "https://duffel.com/docs/api/overview/errors", "code": "not_found" } ] } ``` -------------------------------- ### Example API Response Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/README.md The expected JSON structure returned by the API for an aircraft request. ```json { "data": [ { "name": "Airbus Industries A380", "id": "arc_00009UhD4ongolulWd91Ky", "iata_code": "380" } ] } ``` -------------------------------- ### List Place Suggestions Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Get suggestions for cities and airports by providing a search query and an optional locale. ```typescript const suggestions = await duffel.suggestions.list({ query: 'london' }) console.log(suggestions.data[0].type) // 'city' or 'airport' console.log(suggestions.data[0].name) ``` -------------------------------- ### List Customer User Groups Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/05-stays-cars-payments-identity.md Retrieves a list of all user groups. This method supports pagination, though no options are specified in this example. ```typescript const groups = await duffel.identity.customerUserGroups.list() ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve a specific flight offer by its unique identifier. This method can also include available services in the response. ```APIDOC ## get() ### Description Retrieve an offer by its ID. Optionally include available services in the response. ### Method GET (Implied by SDK method) ### Endpoint `/offers/{id}` (Implied by SDK method) ### Parameters #### Path Parameters - **id** (string) - Required - Duffel's unique identifier for the offer #### Query Parameters - **return_available_services** (boolean) - No - Include available services in response ### Request Example ```typescript const offer = await duffel.offers.get('off_00009hthhsUZ8W4LxQgkjo', { return_available_services: true }) ``` ### Response #### Success Response (200) - **data** (Offer) - The offer object - **meta** (Object) - Metadata about the response #### Response Example (Offer object structure) ``` -------------------------------- ### Handle Incoming Webhook Events Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md This example demonstrates how to set up an Express.js server to receive and process different types of webhook events from the Duffel API. Ensure the endpoint is configured to accept JSON payloads. ```typescript import express from 'express' const app = express() app.post('/webhooks/duffel', express.json(), (req, res) => { const event = req.body switch (event.type) { case 'order.created': console.log('Order created:', event.data.id) break case 'order.updated': console.log('Order updated:', event.data.id) break case 'payment.confirmed': console.log('Payment confirmed:', event.data.id) break default: console.log('Unknown event:', event.type) } res.json({ received: true }) }) ``` -------------------------------- ### Get a Specific Offer by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve a single offer using its unique identifier. Optionally include available services in the response. ```typescript const offer = await duffel.offers.get('off_00009hthhsUZ8W4LxQgkjo', { return_available_services: true }) ``` -------------------------------- ### Sessions - get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md Retrieve a specific session by its ID. This allows you to get details about an existing session link. ```APIDOC ## Sessions - get() ### Description Retrieve a specific session by its ID. This allows you to get details about an existing session link. ### Method GET ### Endpoint /api/v1/links/sessions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Session ID ### Response #### Success Response (200 OK) - **data** (Session) - Session object #### Response Example ```json { "data": { "id": "ses_00009hthhsUZ8W4LxQgkjo", "link_url": "https://duffel.com/e/ses_00009hthhsUZ8W4LxQgkjo", "offer_id": "off_00009hthhsUZ8W4LxQgkjo", "order_id": null, "return_url": "https://myapp.com/checkout", "expires_at": "2024-12-31T23:59:59Z", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Duffel Client Initialization and Resource Access Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/README.md Demonstrates how to initialize the Duffel client and access different API resources like orders, hotels, and identity management. ```APIDOC ## Duffel Client Initialization and Resource Access ### Description Initialize the `Duffel` client with an API token and access various resources such as flight orders, hotel searches, and identity management functions. ### Method Signatures ```typescript const duffel = new Duffel({ token: '...' }) duffel.orders.get('ord_123') // Flight orders duffel.stays.search({...}) // Hotel search duffel.identity.customerUsers.list() // Identity management ``` ### Resource Structure All API resources are accessed through a single `Duffel` client instance. ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve an order cancellation by ID. ```APIDOC ## get() /order_cancellations/{id} ### Description Retrieve an order cancellation by ID. ### Method GET ### Endpoint /order_cancellations/{id} #### Parameters ##### Path Parameters - **id** (string) - Yes - Order cancellation ID #### Response ##### Success Response (200) - **DuffelResponse** - The cancellation object #### Request Example ```typescript const cancellation = await duffel.orderCancellations.get('orc_00009hthhsUZ8W4LxQgkjo') ``` ``` -------------------------------- ### get() - Refunds Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a refund by its unique identifier. ```APIDOC ## get() Refunds ### Description Retrieve a refund by ID. ### Method GET (Implied) ### Endpoint /refunds/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - Refund ID ### Response #### Success Response (200) - **Refund** (object) - The refund object ### Request Example ```typescript const refund = await duffel.refunds.get('ref_00009hthhsUZ8W4LxQgkjo') ``` ``` -------------------------------- ### Initialize Duffel Client using Environment Variables Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Configure the Duffel client by reading settings from environment variables. This approach enhances security by avoiding hardcoded credentials. ```bash # .env DUFFEL_ACCESS_TOKEN=pk_test_abcd1234... DUFFEL_API_VERSION=v2 DUFFEL_DEBUG_VERBOSE=true ``` ```typescript const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN, apiVersion: process.env.DUFFEL_API_VERSION || 'v2', debug: { verbose: process.env.DUFFEL_DEBUG_VERBOSE === 'true' } }) ``` -------------------------------- ### Get Customer User Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/05-stays-cars-payments-identity.md Retrieves a specific customer user by their ID. ```APIDOC ## get() customerUsers ### Description Retrieve a customer user. ### Method `GET` ### Endpoint `/identity/customer_users/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - User ID ### Response #### Success Response (200) - **data** (CustomerUser) - User object ``` -------------------------------- ### BatchOfferRequests.create() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Create a batch of offer requests. ```APIDOC ## BatchOfferRequests.create(options) ### Description Create a batch of offer requests. ### Method POST ### Endpoint /booking/batch-offer-requests ### Parameters #### Request Body - **options.offer_requests** (CreateOfferRequest[]) - Required - Array of offer requests - **options.cabin_class** (CabinClass) - Optional - Cabin class for all requests ### Request Example ```javascript const batch = await duffel.batchOfferRequests.create({ offer_requests: [ { slices: [ { origin: 'LHR', destination: 'JFK', departure_date: '2024-12-25' } ], passengers: [{ type: 'adult' }] }, { slices: [ { origin: 'LHR', destination: 'CDG', departure_date: '2024-12-26' } ], passengers: [{ type: 'adult' }] } ] }) ``` ### Response #### Success Response (200) - **data** (BatchOfferRequest) - Created batch ``` -------------------------------- ### Initialize and Test Duffel Client Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/README.md Import the Duffel module and initialize it with an access token. Use the aircraft endpoint to verify the integration. ```javascript import { Duffel } from '@duffel/api' const duffel = new Duffel({ // Store your access token in an environment variable, keep it secret and only readable on your server token: process.env.DUFFEL_ACCESS_TOKEN, }) // To quickly test whether your integration is working, you can get a single aircraft by its Duffel ID const aircraft = await duffel.aircraft.get('arc_00009VMF8AhXSSRnQDI6Hi') console.log(aircraft) ``` -------------------------------- ### get() - AirlineInitiatedChanges Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific airline-initiated change using its ID. ```APIDOC ## get() AirlineInitiatedChanges ### Description Retrieve an airline-initiated change by ID. ### Method GET (Implied) ### Endpoint /airline-initiated-changes/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - Change ID ### Response #### Success Response (200) - **AirlineInitiatedChange** (object) - The change object ### Request Example ```typescript const change = await duffel.airlineInitiatedChanges.get('aic_00009hthhsUZ8W4LxQgkjo') ``` ``` -------------------------------- ### create() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Create a booking (order) from an offer. This method initiates a new flight booking using a specific offer and passenger details. ```APIDOC ## create() ### Description Create a booking (order) from an offer. ### Method POST ### Endpoint /orders ### Parameters #### Request Body - **offer_id** (string) - Yes - ID of the offer to book - **passengers** (CreateOrderPassenger[]) - Yes - Passenger details for the booking - **type** (PaymentType) - No - Payment type: 'balance' or 'arc_bsp_cash' - **metadata** (Record) - No - Custom metadata ### Response #### Success Response (200) - **data** (Order) - Created order ### Request Example ```javascript const order = await duffel.orders.create({ offer_id: 'off_00009hthhsUZ8W4LxQgkjo', passengers: [ { id: 'pas_00009hthhsUZ8W4LxQgkjo', title: 'mr', given_name: 'John', family_name: 'Doe', email: 'john@example.com' } ], type: 'balance' }) ``` ``` -------------------------------- ### Get Payment Intent Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific payment intent by its unique ID. ```APIDOC ## GET /payment_intents/{id} ### Description Retrieve a payment intent by ID. ### Method GET ### Endpoint `/payment_intents/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - Payment intent ID ### Response #### Success Response (200) - **data** (PaymentIntent) - The payment intent object ### Request Example ```javascript const intent = await duffel.paymentIntents.get('pi_00009hthhsUZ8W4LxQgkjo') console.log(intent.data.client_token) ``` ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve a seat map for a specific flight segment using its ID. ```APIDOC ## get() Seat Map ### Description Retrieve a seat map for a specific flight segment. ### Method GET ### Endpoint /seat-maps/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - Segment ID ### Response #### Success Response (200) - **data** (SeatMap) - Seat map object ### Request Example ```typescript const seatMap = await duffel.seatMaps.get('seg_00009hthhsUZ8W4LxQgkjo') console.log(seatMap.data.cabin) ``` ``` -------------------------------- ### get Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md Retrieve details of a specific webhook subscription using its unique identifier. ```APIDOC ## GET /webhooks/{id} ### Description Retrieve a webhook. ### Method GET ### Endpoint /webhooks/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the webhook to retrieve. ### Response #### Success Response (200) - **webhook** (Webhook) - The retrieved webhook details. ``` -------------------------------- ### Initialize Duffel Client in Live Mode Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Instantiate the Duffel client using a live API token for production environments. Live tokens are prefixed with 'pk_live_'. ```typescript const duffel = new Duffel({ token: 'pk_live_abcd1234...' }) ``` -------------------------------- ### get() - OrderChangeRequests Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific order change request using its unique identifier. ```APIDOC ## GET /order_change_requests/{id} ### Description Retrieve an order change request by its ID. ### Method GET ### Endpoint /order_change_requests/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Duffel's unique identifier for the order change request ### Response #### Success Response (200) - **data** (OrderChangeRequest) - The order change request object ### Request Example ```javascript await duffel.orderChangeRequests.get('ocr_00009hthhsUZ8W4LxQgkjo') ``` ### Response Example ```json { "data": { "id": "ocr_00009hthhsUZ8W4LxQgkjo", "order_id": "ord_00009hthhsUZ8W4LxQgkjo", "type": "change_request", "created_at": "2024-01-01T10:00:00Z", "state": "pending", "slices": [ { "origin": {"iata_code": "LHR"}, "destination": {"iata_code": "CDG"}, "departure_date": "2024-12-26" } ], "potential_pricing": { "total_amount": "100.00", "currency": "GBP" } } } ``` ``` -------------------------------- ### Initialize Duffel Client and Access Resources Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/README.md Instantiate the Duffel client with an API token and demonstrate accessing different API resources like flight orders, hotel searches, and identity management. ```typescript const duffel = new Duffel({ token: '...' }) duffel.orders.get('ord_123') // Flight orders duffel.stays.search({...}) // Hotel search duffel.identity.customerUsers.list() // Identity management ``` -------------------------------- ### List Resources Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/09-quick-reference.md Explains how to list resources such as orders, including manual pagination and automatic pagination using generators. ```APIDOC ## List Resources ### Description This operation allows users to retrieve lists of resources, such as orders. It supports manual pagination using cursors and automatic pagination through generators for easier iteration. ### Method GET ### Endpoint `/orders` (example, applies to other resources like `/flights`, `/payments`, etc.) ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of items to return per page. - **after** (string) - Optional - Cursor for fetching the next page of results. - **before** (string) - Optional - Cursor for fetching the previous page of results. ### Request Example ```json // Get first page { "limit": 50 } // Get next page using cursor { "limit": 50, "after": "cursor_string" } ``` ### Response #### Success Response (200) - **data** (array) - A list of resource objects. - **meta** (object) - Pagination metadata. - **after** (string) - Cursor for the next page. - **before** (string) - Cursor for the previous page. #### Response Example ```json { "data": [ { "id": "ord_...", // ... order details } ], "meta": { "after": "next_cursor_string", "before": "previous_cursor_string" } } ``` ### Automatic Pagination ```typescript // Using a generator for automatic pagination for await (const order of duffel.orders.listWithGenerator({ limit: 50 })) { console.log(order.data.id) } ``` ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve an order by its ID. This method fetches a specific order using its unique identifier. ```APIDOC ## get() ### Description Retrieve an order by its ID. ### Method GET ### Endpoint /orders/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - Duffel's unique identifier for the order ### Response #### Success Response (200) - **data** (Order) - The order object ### Request Example ```javascript const order = await duffel.orders.get('ord_00009hthhsUZ8W4LxQgkjo') console.log(order.data.id) ``` ``` -------------------------------- ### Basic Duffel API JavaScript Usage Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/00-index.md Demonstrates how to initialize the Duffel client, search for flights, list available offers, and book a flight using the Duffel API. ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN }) // Search for flights const offerRequest = await duffel.offerRequests.create({ slices: [{ origin: 'LHR', destination: 'JFK', departure_date: '2024-12-25' }], passengers: [{ type: 'adult' }], cabin_class: 'economy' }) // Get available offers const offers = await duffel.offers.list({ offer_request_id: offerRequest.data.id }) // Book a flight const order = await duffel.orders.create({ offer_id: offers.data[0].id, passengers: [{ id: offers.data[0].passengers[0].id, title: 'mr', given_name: 'John', family_name: 'Doe', gender: 'm', born_on: '1990-01-01', email: 'john@example.com', phone_number: '+442071838750' }], type: 'balance' }) console.log(`Order confirmed: ${order.data.id}`) ``` -------------------------------- ### create() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Create a new partial offer request, typically used for flexible date flight searches. ```APIDOC ## create() ### Description Create a partial offer request for flexible date searches. ### Method POST ### Endpoint /booking/partial-offer-requests ### Parameters #### Request Body - **options.slices** (PartialOfferRequestSlice[]) - Yes - Flight segments - **options.passengers** (CreateOfferRequestPassenger[]) - Yes - Passengers - **options.cabin_class** (CabinClass) - No - Preferred cabin class ### Request Example ```typescript const partial = await duffel.partialOfferRequests.create({ slices: [ { origin: 'LHR', destination: 'JFK', departure_date_from: '2024-12-20', departure_date_to: '2024-12-25' } ], passengers: [{ type: 'adult' }] }) ``` ### Response #### Success Response (200) - **PartialOfferRequest** - Created partial request ``` -------------------------------- ### Importing Types and Client Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/00-index.md Demonstrates how to import the Duffel client, core data types like 'Order' and 'Offer', and the 'DuffelError' class for type-safe API interactions. ```typescript import { Duffel, Order, Offer, DuffelError } from '@duffel/api' const order: Order = (await duffel.orders.get('ord_123')).data const offers: Offer[] = (await duffel.offers.list({...})).data ``` -------------------------------- ### Get Airport by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Retrieve a specific airport's details using its unique identifier (IATA code). ```typescript const airport = await duffel.airports.get('LHR') console.log(airport.data.name) // 'Heathrow' console.log(airport.data.iata_code) // 'LHR' ``` -------------------------------- ### Initialize Duffel Client with API Version Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Specify the API version to use. Defaults to 'v2'. ```typescript const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN, apiVersion: 'v2' }) ``` -------------------------------- ### Get Refund by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific refund using its unique identifier. Requires the refund ID as a string parameter. ```typescript const refund = await duffel.refunds.get('ref_00009hthhsUZ8W4LxQgkjo') ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Retrieve airport details by ID. This method allows fetching specific airport information using its unique identifier. ```APIDOC ## get() /airports/{id} ### Description Retrieve airport details by ID. This method allows fetching specific airport information using its unique identifier. ### Method GET ### Endpoint /airports/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Duffel's unique identifier for the airport (IATA code) ### Response #### Success Response (200) - **data** (Airport) - Airport object #### Response Example { "data": { "iata_code": "LHR", "name": "Heathrow" } } ``` -------------------------------- ### create() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Create a new offer request to search for flights. This method allows specifying flight segments, passengers, and other preferences. ```APIDOC ## create(options: CreateOfferRequest & CreateOfferRequestQueryParameters) ### Description Create a new offer request to search for flights. ### Method POST (assumed based on typical RESTful patterns for creation) ### Endpoint /offer_requests ### Parameters #### Request Body - **slices** (OfferRequestSlice[]) - Yes - Array of flight segments - **slices[].origin** (Place) - Yes - Origin city/airport - **slices[].destination** (Place) - Yes - Destination city/airport - **slices[].departure_date** (string) - Yes - Departure date (ISO 8601) - **passengers** (CreateOfferRequestPassenger[]) - Yes - Array of passenger objects - **cabin_class** (CabinClass) - No - Preferred cabin class: 'economy', 'premium_economy', 'business', 'first' - **return_offers** (boolean) - No - Include offers in response (default: `true`) - **supplier_timeout** (number) - No - Timeout in milliseconds for supplier responses - **view** ('default' | 'itineraries') - No - Response format: 'default' or 'itineraries' ### Response #### Success Response (200) - **data** (OfferRequest) - Created offer request ### Request Example ```javascript const offerRequest = await duffel.offerRequests.create({ slices: [ { origin: 'LHR', destination: 'JFK', departure_date: '2024-12-25' } ], passengers: [ { type: 'adult' }, { age: 14 } ], cabin_class: 'economy', return_offers: true }) console.log(offerRequest.data.id) console.log(offerRequest.data.offers) ``` ``` -------------------------------- ### Import Main Client Classes and Types Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/09-quick-reference.md Import the main client class, error class, and helper functions from the '@duffel/api' package. ```typescript import { Duffel, DuffelError, hasService, hasAvailableSeatService } from '@duffel/api' ``` -------------------------------- ### Configure Duffel Client with Verbose Logging Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/README.md Initialize the Duffel client with an access token and enable verbose debug mode. This is useful for inspecting API calls and their arguments during development. ```javascript const duffel = new Duffel({ // We recommend storing your access token in an environment variable for security token: process.env.DUFFEL_ACCESS_TOKEN, debug: { verbose: true }, }) ``` -------------------------------- ### Get Order by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve a specific order using its unique identifier. This is useful for fetching the latest details of an existing booking. ```typescript const order = await duffel.orders.get('ord_00009hthhsUZ8W4LxQgkjo') console.log(order.data.id) ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Retrieve airline details by ID. This method fetches a single airline's information using its unique Duffel identifier. ```APIDOC ## get(id: string) ### Description Retrieve airline details by ID. This method fetches a single airline's information using its unique Duffel identifier. ### Parameters #### Path Parameters - **id** (string) - Required - Duffel's unique identifier for the airline ### Response #### Success Response `Promise>` — Airline object ### Request Example ```typescript const airline = await duffel.airlines.get('aln_00001876aqC8c5umZmrRds') console.log(airline.data.name) // 'British Airways' console.log(airline.data.iata_code) // 'BA' ``` ``` -------------------------------- ### get() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/04-supporting-resources-api.md Retrieve aircraft details by ID. This method fetches a single aircraft's information using its unique Duffel identifier. ```APIDOC ## get() Aircraft ### Description Retrieve aircraft details by ID. This method fetches a single aircraft's information using its unique Duffel identifier. ### Method GET (assumed based on 'get' and typical REST patterns) ### Endpoint /airports/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Duffel's unique identifier for the aircraft ### Response #### Success Response (200) - **data** (Aircraft) - Aircraft object #### Response Example { "data": { "id": "arc_00009VMF8AhXSSRnQDI6Hi", "name": "Airbus Industries A380", "iata_code": "380" } } ``` -------------------------------- ### Initialize Duffel Client Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/09-quick-reference.md Initialize the Duffel client with your API token and optional configuration parameters like basePath, apiVersion, debug, and source. ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: 'pk_test_...', basePath: 'https://api.duffel.com', apiVersion: 'v2', debug: { verbose: false }, source: 'my-app' }) ``` -------------------------------- ### Sessions - create() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/08-additional-resources.md Create a new session link to share booking experiences. You can optionally pre-populate it with an offer ID, order ID, set a return URL, or specify an expiration time. ```APIDOC ## Sessions - create() ### Description Create a new session link to share booking experiences. You can optionally pre-populate it with an offer ID, order ID, set a return URL, or specify an expiration time. ### Method POST ### Endpoint /api/v1/links/sessions ### Parameters #### Request Body - **offer_id** (string) - Optional - Offer ID to pre-populate - **order_id** (string) - Optional - Order ID for modification - **return_url** (string) - Optional - URL to return to after completion - **expires_at** (string) - Optional - Session expiration (ISO 8601) ### Request Example ```json { "offer_id": "off_00009hthhsUZ8W4LxQgkjo", "return_url": "https://myapp.com/checkout", "expires_at": "2024-12-31T23:59:59Z" } ``` ### Response #### Success Response (201 Created) - **data** (Session) - Created session object containing the shareable link #### Response Example ```json { "data": { "id": "ses_00009hthhsUZ8W4LxQgkjo", "link_url": "https://duffel.com/e/ses_00009hthhsUZ8W4LxQgkjo", "offer_id": "off_00009hthhsUZ8W4LxQgkjo", "order_id": null, "return_url": "https://myapp.com/checkout", "expires_at": "2024-12-31T23:59:59Z", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Initialize Duffel Client with Access Token Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/07-errors-and-configuration.md Initialize the Duffel client with your API access token. It's recommended to store the token in an environment variable for security. ```typescript const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN }) ``` -------------------------------- ### Duffel Client Constructor Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/01-client-initialization.md Initializes the Duffel API client with a configuration object. The configuration includes the API token, optional base path, API version, debug settings, and a custom source identifier. ```APIDOC ## Duffel Client Constructor ### Description Initializes the Duffel API client with a configuration object. The configuration includes the API token, optional base path, API version, debug settings, and a custom source identifier. ### Constructor Signature ```typescript class Duffel { constructor(config: Config) } ``` ### Parameters #### Constructor Parameters - **config** (`Config`) - Required - Configuration object for the Duffel client - **config.token** (`string`) - Required - API access token from your Duffel dashboard - **config.basePath** (`string`) - Optional - Default: `'https://api.duffel.com'` - Base URL for API requests - **config.apiVersion** (`string`) - Optional - Default: `'v2'` - API version to use - **config.debug** (`SDKOptions`) - Optional - Debug configuration object - **config.debug.verbose** (`boolean`) - Optional - When `true`, logs endpoint, method, and query parameters to console - **config.source** (`string`) - Optional - Custom source identifier for tracking requests ### Example ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN, debug: { verbose: true } }) // Access resources via properties const aircraft = await duffel.aircraft.get('arc_00009VMF8AhXSSRnQDI6Hi') ``` ### Public Properties The Duffel client exposes the following resource collections: | Property | Type | Description | |---|---|---| | `aircraft` | `Aircraft` | Supporting resource for aircraft information | | `airlines` | `Airlines` | Supporting resource for airline information | | `airports` | `Airports` | Supporting resource for airport information | | `batchOfferRequests` | `BatchOfferRequests` | Create batch flight offer requests | | `offerRequests` | `OfferRequests` | Search for flight offers | | `offers` | `Offers` | Retrieve flight offers | | `orders` | `Orders` | Create and manage flight bookings | | `orderChangeRequests` | `OrderChangeRequests` | Request changes to orders | | `orderChangeOffers` | `OrderChangeOffers` | Retrieve offers for order changes | | `orderChanges` | `OrderChanges` | Apply order changes | | `orderCancellations` | `OrderCancellations` | Cancel orders | | `payments` | `Payments` | Record payments for orders | | `seatMaps` | `SeatMaps` | Retrieve seat maps for flights | | `paymentIntents` | `PaymentIntents` | Create payment intents for card payments | | `partialOfferRequests` | `PartialOfferRequests` | Create partial offer requests | | `suggestions` | `Suggestions` | Get place suggestions for cities and airports | | `refunds` | `Refunds` | Manage refunds for payments | | `webhooks` | `Webhooks` | Configure webhooks for event notifications | | `stays` | `Stays` | Hotel accommodation search and booking | | `cars` | `Cars` | Car rental search and booking | | `cards` | `Cards` | Payment card management (uses separate endpoint) | | `three_d_secure_sessions` | `ThreeDSecureSessions` | 3D Secure payment sessions | | `identity` | `Identity` | Identity and authentication management | | `links` | `Sessions` | Link creation and session management | | `airlineInitiatedChanges` | `AirlineInitiatedChanges` | Airline-initiated order changes | ``` -------------------------------- ### Full Flight Booking Workflow Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/README.md This snippet demonstrates the complete process of searching for flights, retrieving available offers, and booking an order using the Duffel API. Ensure your DUFFEL_ACCESS_TOKEN environment variable is set. ```typescript import { Duffel } from '@duffel/api' const duffel = new Duffel({ token: process.env.DUFFEL_ACCESS_TOKEN }) // Search for flights const search = await duffel.offerRequests.create({ slices: [{ origin: 'LHR', destination: 'JFK', departure_date: '2024-12-25' }], passengers: [{ type: 'adult' }] }) // Get offers const offers = await duffel.offers.list({ offer_request_id: search.data.id }) // Book const order = await duffel.orders.create({ offer_id: offers.data[0].id, passengers: [{ id: offers.data[0].passengers[0].id, title: 'mr', given_name: 'John', family_name: 'Doe', gender: 'm', born_on: '1990-01-01', email: 'john@example.com', phone_number: '+442071838750' }], type: 'balance' }) console.log(`Booked: ${order.data.id}`) ``` -------------------------------- ### Get Airline-Initiated Change by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific airline-initiated change using its unique identifier. Requires the change ID as a string parameter. ```typescript const change = await duffel.airlineInitiatedChanges.get('aic_00009hthhsUZ8W4LxQgkjo') ``` -------------------------------- ### Configure Duffel Access Token Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/examples/with-next/README.md Add your Duffel API access token to the .env.local file in the project root. ```text DUFFEL_ACCESS_TOKEN= ``` -------------------------------- ### list() Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/02-flight-booking-api.md Retrieve a paginated list of offer requests. This method supports pagination to efficiently fetch multiple offer requests. ```APIDOC ## list(options?: PaginationMeta) ### Description Retrieve a paginated list of offer requests. ### Method GET (assumed based on typical RESTful patterns for retrieval) ### Endpoint /offer_requests ### Parameters #### Query Parameters - **limit** (number) - No - Number of results per page (1-200) (Default: 50) - **after** (string) - No - Cursor for pagination (next page) - **before** (string) - No - Cursor for pagination (previous page) ### Response #### Success Response (200) - **data** (OfferRequest[]) - Array of offer request objects - **meta** (PaginationMeta) - Pagination metadata including cursors for next/previous pages ### Request Example ```javascript const page = await duffel.offerRequests.list({ limit: 20 }) console.log(page.data.length) console.log(page.meta.after) // Use for pagination ``` ``` -------------------------------- ### Get Payment by ID Source: https://github.com/duffelhq/duffel-api-javascript/blob/main/_autodocs/03-order-management-api.md Retrieve a specific payment using its unique identifier. This is useful when you need to check the status or details of a single payment. ```typescript get(id: string): Promise> ``` ```typescript const payment = await duffel.payments.get('pay_00009hthhsUZ8W4LxQgkjo') ```