# Ferry VN SDK & API Quickstart

Source: https://ferry.vn/en/ferry-vn-sdk-rest-api-developer-quickstart/
Locale: en
Category: Ferry API & Tech
Published: 2026-11-25
Updated: 2026-11-25
Author: Le Quoc Khoi (CEO, Ferry VN JSC) — https://ferry.vn/en/author/le-quoc-khoi/
Summary: Ferry VN SDK REST API quickstart with @ferryvn/sdk: Bearer key scopes, zero-cost uatexpress UAT, bookingDrafts validation, 50-row paging, and error codes.

---

> **Key Takeaways:** Completing this **Ferry VN SDK REST API quickstart** with **Ferry VN JSC** connects your backend to 15+ Vietnamese ferry operators through 9 public catalog routes, 86 authenticated `/api/v1/` partner routes, and the zero-dependency `@ferryvn/sdk` TypeScript client.
>
> - **Zero-Cost UAT Isolation:** Point development builds to `https://api.ferryvn.net` (`environment: 'uat'`), where `OPERATOR_ADAPTER_ALLOWLIST=uatexpress` blocks real carriers and exposes the simulated `uatexpress` operator for full booking, PDF issuance, and cancellation testing.
> - **Server-Side Scoped Auth:** Authenticate exclusively via `Authorization: Bearer <API_KEY>` using Dashboard-issued scoped presets (`partner_ota`, `read_only`, `tenant_website`, `full`), with zero-downtime key rotation (`1h`, `24h`, or `7d` grace).
> - **Pre-Validated Booking Drafts:** Use `ferry.bookingDrafts.create()` to validate passenger ages, nationality fare tiers, duplicate IDs, seat sellability, and harbor fees locally before calling `POST /api/v1/bookings`.
> - **Explicit Non-GDS Boundaries:** There are no upstream hard seat holds, no creation idempotency keys, a 50-record pagination ceiling, and 4 schedule-lookup-only Production adapters to filter before checkout.

Following a dedicated **Ferry VN SDK REST API quickstart** prevents travel-tech integrations from breaking on maritime constraints that differ sharply from flights or hotels. Vietnamese island ferries enforce strict passenger manifest fields, Vietnam local calendar dates, asymmetric confirmation latency, and pre-funded VND settlement chains that diverge from airline Global Distribution Systems (GDS).

Skipping environment isolation or shipping naive retry middleware causes duplicate bookings, ghost seat claims, or unintended production debits. Below are the verified UAT settings, Bearer key scopes, runnable `@ferryvn/sdk` steps from pier discovery to boarding PDFs, pagination and error conventions, and the Production cutover checklist.

## Environments, UAT Isolation, and Prerequisites

Ferry VN operates separate UAT and Production environments with independent databases, API key stores, and OpenAPI portals at `/docs`. Production (`https://api.ferry.vn`) connects 12 live operator adapters (8 ticketing + 4 schedule lookup), while UAT (`https://api.ferryvn.net`) enforces `OPERATOR_ADAPTER_ALLOWLIST=uatexpress` so teams test simulated **UAT Express (`uatexpress`)** sailings at zero real cost.

![Environment isolation between api.ferryvn.net (uatexpress UAT) and api.ferry.vn (Production) with scoped Bearer key presets](https://cdn.ferry.vn/media/31/diagram-en-sdk-quickstart-uat-vs-production.webp)

| Configuration Attribute | UAT Environment (`uat`) | Production Environment (`production`) | Developer Action |
|---|---|---|---|
| **Base URL** | `https://api.ferryvn.net` | `https://api.ferry.vn` | Select `environment: 'uat'` in `@ferryvn/sdk` or set `baseUrl` |
| **OpenAPI Portal** | `https://api.ferryvn.net/docs` | `https://api.ferry.vn/docs` | Inspect live request schemas per environment |
| **Active Operators** | Simulated `uatexpress` only (real carriers blocked) | 12 real adapters (8 ticketing + 4 schedule lookup) | Query `UAT ...` piers on UAT and filter 4 lookup-only carriers on Prod |
| **Financial Impact** | Zero real cost (simulated balance and credit) | Live VND wallet debit and approved credit line | Run error, partial-leg, and cancellation tests freely on UAT |
| **VAT E-Invoices** | MISA meInvoice test environment (no tax validity) | Live VAT e-invoices per operator/agency config | Validate invoice webhooks on UAT without emailing real buyers |
| **Data Retention & PII** | Periodically refreshed from Production | Persistent commercial records | Use synthetic passenger data only on UAT |

On UAT, `uatexpress` mirrors Phu Quoc Express logic across three round-trip corridors (`UAT Rach Gia–Phu Quoc`, `UAT Ha Tien–Phu Quoc`, and `UAT Tran De–Con Dao` with VND 18,000 harbor fee), scheduling four daily sailings up to 29 days ahead across ECO and VIP cabins. Real schedules appear in UAT search, yet booking real carriers on UAT fails by design. Request isolated test credentials via [Ferry VN's API partner onboarding](/en/api-partners/), or review full corridor coverage in the [Unified Vietnam Ferry API specification](/en/vietnam-ferry-api-unified-multi-operator-integration/).

## Authentication, Resource Scopes, and Key Presets

Organization administrators generate API keys in the Agency Dashboard (`Settings > API Keys`), where keys display once because Ferry VN stores only a SHA-512 hash. Requests pass `Authorization: Bearer <API_KEY>` (`X-API-Key` is ignored), and `@ferryvn/sdk` blocks browser initialization by default when an `apiKey` is present.

### Scope Presets and Least-Privilege Access

Provision scoped keys per backend service (`<resource>:read` and `<resource>:write`, where `write` implies `read`) via [Ferry VN's API & SDK platform suite](/en/platform/api-sdk/) instead of using wildcard `*` keys everywhere.

| Dashboard Preset | Included Resource Scopes | Recommended Workload | Key Security Controls |
|---|---|---|---|
| **`partner_ota`** | `voyages:read`, `bookings:write`, `payments:read` | Production OTA search, booking, issuance, and ledger reads | Blocks organization settings and user admin mutations |
| **`read_only`** | `voyages:read`, `bookings:read`, `customers:read`, `payments:read`, `vouchers:read`, `reports:read`, `organizations:read`, `files:read` | Analytics, reconciliation jobs, read-only support | Zero write access across bookings and money flows |
| **`tenant_website`** | `auth:write`, `voyages:read`, `vouchers:read`, `organizations:read` | Storefront server calls alongside visitor JWT sessions | Excludes server-level booking and payment mutations |
| **`full`** | `*` (wildcard administrative access) | Controlled internal scripts or migrations | Pair with IP allowlist (up to 50 CIDRs) and expiration |

Keys support two-year max expiration, per-key rate caps (`10–10,000 req/min`), 50 IPv4/IPv6 CIDRs, and **Rotate with grace** (`1h`, `24h`, or `7d`) for zero-downtime secret rollouts.

### Installing `@ferryvn/sdk` and Initializing `FerryClient`

The zero-dependency TypeScript client lives in [`ferry-vn/ferry-sdk` on GitHub](https://github.com/ferry-vn/ferry-sdk) alongside `@ferryvn/cli` and `@ferryvn/mcp`, published together on [npm](https://www.npmjs.com/package/@ferryvn/sdk) for Node.js 20+, Bun, Deno, and Cloudflare Workers.

```bash
npm install @ferryvn/sdk
```

```ts
import { FerryClient, todayInVietnam, addDays } from '@ferryvn/sdk'

const ferry = new FerryClient({
  apiKey: process.env.FERRY_UAT_API_KEY,
  environment: 'uat', // resolves to https://api.ferryvn.net/api/v1
  timeoutMs: 30_000
})

const travelDate = addDays(todayInVietnam(), 3)
```

Passing UTC server dates causes off-by-one departure dates between `17:00` and `23:59` UTC. Always use `toYmd`, `todayInVietnam`, or `addDays` for `YYYY-MM-DD` search queries, and convert returned ISO-8601 timestamps to GMT+7 on display.

## End-to-End Integration Flow: Search to Issued Ticket

A clean integration separates read-side discovery from Ferry VN's two-stage transactional write lifecycle. Use `ferry.bookingDrafts` rather than assembling raw 17-field payloads so age brackets, seat sellability, and harbor fees validate locally first.

![Five-step @ferryvn/sdk integration sequence from pier lookup and bookingDrafts validation to confirmToIssue](https://cdn.ferry.vn/media/31/diagram-ferry-api-two-stage-booking-lifecycle.webp)

### Step 1: Pier Discovery, Voyage Search, and Live Pricing

Cache the 9 unauthenticated public catalog endpoints (piers, routes, operators) for 24 hours, then search synced voyages and inspect live fares before checkout.

```ts
import { isVoyageBookable, formatVnd } from '@ferryvn/sdk'

// 1. Resolve UAT piers (accent-insensitive search)
const [from] = await ferry.locations.find('UAT Tran De')
const [to] = await ferry.locations.find('UAT Con Dao')

// 2. Search synced voyages on the Vietnam calendar date
const { data: voyages } = await ferry.voyages.search({
  date: travelDate,
  departureId: from.id,
  destinationId: to.id
})

const bookable = voyages.filter(isVoyageBookable)
if (bookable.length === 0) {
  throw new Error('No bookable UAT voyages found for selected date')
}

// 3. Check route prices (live: 3 refreshes up to 10 voyages from seat maps)
const routePrices = await ferry.prices.forRoute({
  departureId: from.id,
  destinationId: to.id,
  date: travelDate,
  live: 3
})

console.log(bookable[0].voyage.id, formatVnd(routePrices[0]?.priceVnd ?? 0))
```

Because voyage search reflects cached snapshots (refreshed every 30 minutes within 7 days), always fetch a fresh seat layout right before booking as covered in our [live availability sync architecture guide](/en/live-availability-inventory-sync-island-ferries/).

### Step 2: Pre-Validating and Creating a Booking Draft

`bookingDrafts.prepare()` quotes exact VND totals locally, while `bookingDrafts.create()` runs identical checks (age tiers, unique IDs, vacant seats, harbor fees) and posts `POST /api/v1/bookings`.

```ts
// 4. Locate or create a customer profile (synthetic data only on UAT)
const [customer] = await ferry.customers.search('0900000001')

// 5. Validate locally and create a Requested (status 2), unpaid booking
const { booking, draft } = await ferry.bookingDrafts.create({
  customerId: customer.id,
  ordererName: 'Jordan Vance',
  contactEmail: 'uat-qa@partner-ota.example',
  depart: {
    voyageId: bookable[0].voyage.id,
    seats: ['A1'], // omit seats to let the SDK auto-assign adjacent seats
    passengers: [
      {
        name: 'JORDAN VANCE',
        dateOfBirth: '1991-06-14',
        socialId: 'UAT99001122',
        nationality: 'AU'
      }
    ]
  }
})

console.log({
  bookingId: booking.id,
  status: booking.status, // 2 = Requested
  estimatedTotalVnd: draft.estimatedTotalVnd,
  paymentExpiredAt: booking.payment_expired_at
})
```

Creating a booking marks seats inside Ferry VN without locking them on the carrier's direct engine and without deducting funds. Every traveler (including infants and children) must supply full name, date or year of birth, passport or ID number, and nationality per [Vietnam passenger manifest rules](/en/maritime-passenger-manifest-e-ticket-qr-vietnam/).

### Step 3: Confirming Issuance, Polling, and Ticket Download

Calling `bookings.confirmToIssue(booking.id)` validates passenger completeness, checks balance/credit hierarchy, deducts your VND NET rate, and dispatches carrier ticketing.

```ts
// 6. Trigger issuance (SDK sets a 10-minute minimum timeout; never retries writes)
await ferry.bookings.confirmToIssue(booking.id)

// 7. Poll authoritative booking state until terminal status (10 Issued or 6 Issue Error)
let current = await ferry.bookings.get(booking.id)
while (current.status === 2) {
  await new Promise((resolve) => setTimeout(resolve, 4_000))
  current = await ferry.bookings.get(booking.id)
}

if (current.status !== 10) {
  throw new Error(`Issuance stopped at status ${current.status}`)
}

// 8. Download issued boarding pass PDF (re-downloadable at zero extra cost)
const pdfResponse = await ferry.request('GET', `/api/v1/bookings/download-ticket/${booking.id}`)
```

On UAT, `uatexpress` returns single-page boarding PDFs immediately. On Production, issuance latency depends on each operator's infrastructure (seconds to 5–8 minutes), making `GET /api/v1/bookings/{id}` polling authoritative.

## Pagination, Sorting, Error Shapes, and Write Safety

Four REST contract conventions trip up integrations expecting standard CRUD behavior:

1. **Silent pagination clamping and sort fallback:** List endpoints default to 10 items, clamp `limit` silently at 50 (100 on routes/tables), and ignore custom sort keys (falling back to descending `_id`). Iterate all cursors and sort in memory.
2. **Three concurrent error shapes:** Auth/routing errors (401/403/404) return timestamp and path without business codes, business errors return HTTP 422 with six-digit codes (or flat field maps), and server errors return HTTP 500. Branch on numeric codes rather than text strings.
3. **Swallowed empty arrays on HTTP 200:** Transient database/auth faults on list queries can return HTTP 200 `[]`. Never purge local caches from one empty response.
4. **No idempotency keys on writes:** `@ferryvn/sdk` retries `GET`/`HEAD` up to twice (`408`, `429`, `502`, `503`, `504`) and never retries `POST`/`PATCH`. Note also the exact single-`p` path `POST /api/v1/vouchers/check-aplicability`.

| Error Signal / SDK Class | Six-Digit Code | Meaning | Safe Partner Action |
|---|---|---|---|
| `FerryValidationError` (422) | `150201` (`UnavailableSeats`) | Another channel claimed the seat before issuance | Refresh boat layout and prompt customer to select another seat |
| `FerryValidationError` (422) | `120145` (`PassengerInfoIncomplete`) | Missing mandatory VIMAWA passenger field at issuance | Populate missing fields before calling `confirmToIssue` |
| `FerryValidationError` (422) | `120100` | Active 600s issuance lock (or 180s payment lock) | Wait at least 60 seconds and poll `bookings.get(id)` |
| `FerryValidationError` (422) | `120140` | Cluster cooldown (>5 confirmation tries in 60s for booking) | Stop bursting and poll booking status after 60 seconds |
| `FerryRateLimitError` (429) | `ApiKeyRateLimited` or IP/booking cap | Exceeded 5,000/10s IP cap, per-key cap, or 5/60s `IP + bookingId` cap | Honor `Retry-After` seconds with jittered backoff |
| `FerryValidationError` (422) | `120120` / `120205` / `160105` | Insufficient organization balance for booking or cancel fee | Do not retry automatically, top up VND wallet first |
| `FerryPermissionError` (403) | None (90xxxx hidden internally) | Missing scope, cross-org ID, or transient auth outage | Probe a public route and retry once before escalating |

When a timeout interrupts `bookingDrafts.create()`, never resend `POST /api/v1/bookings` automatically. Query recent orders via cursor iteration first:

```ts
import { FerryConnectionError } from '@ferryvn/sdk'

async function findExistingBooking(contact: string, voyageId: string) {
  for await (const item of ferry.bookings.iterate({ namePhoneEmail: contact, limit: 50 })) {
    const matchesVoyage = item.orders?.some((leg) => leg.voyageId === voyageId)
    if (matchesVoyage && item.status === 2) {
      return item
    }
  }
  return null
}

try {
  // Attempt creation once with no automatic write retries
} catch (error) {
  if (error instanceof FerryConnectionError) {
    const recovered = await findExistingBooking('uat-qa@partner-ota.example', bookable[0].voyage.id)
    if (recovered) {
      // Reuse recovered.id for confirmToIssue instead of creating a duplicate
    }
  }
  throw error
}
```

Review raw-body HMAC-SHA256 verification and daily reconciliation sweeps in our [ferry API reliability and reconciliation patterns guide](/en/ferry-api-reliability-reconciliation-patterns/).

## UAT Verification Checklist and Production Cutover

Before swapping UAT keys for Production credentials in your Agency Dashboard, validate five launch gates against `uatexpress` on `https://api.ferryvn.net`:

1. **Error-path coverage:** Trigger `150201` (`UnavailableSeats`), `150105` (`DuplicateSocialId`), closed-voyage rejection, post-issuance passenger updates, and cancellation tiers on UAT.
2. **Filter 4 schedule-only Production carriers:** Out of 12 Production adapters, 8 support ticket issuance (`PhuQuocExpress`, `SuperDong`, `GreenLines`, `Lightning68`, `HoaBinhShip`, `PhuQuyExpress`, `ChanKhaLuxury`, and semi-automated `CangSaKy`), while 4 (`BinhAnHaTien`, `ThanhThoi`, `HangChauTourist`, `SaiGonWaterGo`) are schedule/fare lookup only.
3. **Isolate secrets & `x-request-id`:** Use `partner_ota` rather than `*`, keep live PII off UAT, and log `x-request-id` UUIDs on every request.
4. **Configure opt-in HMAC-SHA256 webhooks:** Rotate `whsec_...` secrets cleanly, verify exact raw bytes, return HTTP 2xx within 2 seconds, and run daily booking status sweeps.
5. **Validate wallet & NET layers:** Fund your VND wallet and confirm vouchers discount retail totals without altering `confirmToIssue` NET debits.

Inspect interactive endpoints in the [live Scalar API reference](https://api.ferry.vn/docs) and implementation examples in the [official TypeScript SDK and webhook docs](https://docs.ferry.vn/en/developers/), or contact our engineering desk at `hi@ferry.vn` (`+84 924 299 898`).

## Frequently Asked Questions

| Question | Answer |
| --- | --- |
| Does `@ferryvn/sdk` work in browsers or non-Node JavaScript runtimes? | @ferryvn/sdk has zero runtime dependencies and runs on Node.js 20+, Bun, Deno, and Cloudflare Workers. It intentionally refuses to initialize in browser runtimes when an API key is supplied because keys carry server-side organizational privileges. Only unauthenticated catalog calls are safe client-side. |
| Why does booking a real operator fail on the Ferry VN UAT environment? | On UAT ( https://api.ferryvn.net ), Ferry VN enforces OPERATOR_ADAPTER_ALLOWLIST=uatexpress so live ferry carriers remain completely isolated. Real carrier schedules still appear in search results copied from Production, so developers must search UAT ... piers and book simulated uatexpress voyages for zero-cost testing. |
| How should my backend handle a network timeout during `bookings.create`? | Never retry POST /api/v1/bookings automatically because the Partner API has no idempotency keys and a second call creates a duplicate booking. Instead, query bookings.list filtered by passenger contact, voyage ID, and travel date, then reuse the existing booking ID if found. |
| Which Production ferry operators support automated API ticketing versus schedule lookup only? | Production connects 12 real operator adapters: 8 support ticket issuance ( PhuQuocExpress , SuperDong , GreenLines , Lightning68 , HoaBinhShip , PhuQuyExpress , ChanKhaLuxury , and semi-automated CangSaKy ), while 4 ( BinhAnHaTien , ThanhThoi , HangChauTourist , SaiGonWaterGo ) support schedule and fare lookup only. |
| Can I sort voyage search results by departure time or lowest fare via query parameters? | No. Ferry VN list endpoints ignore custom sort fields and fall back to descending _id order while silently clamping page sizes to 50 records. Fetch all pages by following next_cursor (or ferry.voyages.iterate() ), then sort results locally in your application layer. |
