> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gomarketbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create a package booking with a slate

> Book every session of a package in one call — build a slate for the recurring pattern, create the PACKAGE order item, then book the whole slate by id.

This guide walks through the flow for booking a **package** — a block of
session credits redeemed across N recurring sessions (e.g. "8 swim lessons,
Mon/Wed/Fri"). Instead of finding and booking each session one at a time, you
build one **slate** — a complete, server-resolved N-session plan — and book
the whole thing with a single call.

It builds on [The booking engine model](https://docs.gomarketbox.com/concepts/booking-engine-model.md) —
read that first if you haven't, especially the [Slates](https://docs.gomarketbox.com/concepts/booking-engine-model.md#slates)
section. This guide also assumes the [BFF pattern](https://docs.gomarketbox.com/guides/booking-flow-auth.md#the-bff-pattern)
and an API key already set up.

> [!NOTE]
>
> Every request in this guide is authenticated with the `x-api-key` header,
> attached server-side by your BFF — never in the browser.

> [!NOTE]
>
> **Prerequisite: the service needs an active `PACKAGE` business
> model.** Package creation (`POST /services/{serviceId}/offerings/{offeringId}/packages`)
> fails with `400` if the parent service doesn't have one enabled. Business
> models are set at the **service** level, not per-offering, so enabling it
> makes packages creatable across every offering on that service.
>
> Every booking created from a package — including via holds → convert — is
> stamped `businessModelType: "PACKAGE"` with `packageOrderItemId`
> set, never `SINGLE_BOOKING`. Keep that in mind for reporting/analytics that
> segment bookings by business model.

## How it works

A package booking is four calls, always in this order:

1. **Find the package.** `GET /services/{serviceId}/packages?status=ACTIVE`
   lists every sellable bundle on the service, across all of its offerings —
   the call a storefront makes before the client has picked an option. It
   gives you the `packageId` every later step needs.
2. **Build the slate.** `POST /availability/package-slate` with the
   `packageId`, a location, and an `rrule` (recurrence pattern) returns a
   `primarySlate` — the best single supplier's plan that fills every
   session — with a `slateId`.
3. **Create the order.** `POST /orders` with one `PACKAGE` item is what makes
   the package purchasable — it's the order item every session will draw
   down. The server derives the service, offering, session count, and price
   from the package.
4. **Book the slate.** `POST /orders/{orderId}/package-bookings` with
   `{ orderItemId, idempotencyKey, slateId }` creates all N bookings
   atomically — up to 15 sessions with the default `all_or_nothing`. You
   never copy times or locations out of the slate response by hand — the
   server re-resolves every session itself.

```mermaid theme={null}
sequenceDiagram
    participant B as Browser
    participant BFF as Your BFF
    participant MB as MarketBox API
    B->>BFF: Start a package booking
    BFF->>MB: GET .../services/{serviceId}/packages?status=ACTIVE
    MB-->>BFF: { data: [{ packageId, creditCount, pricing }] }
    BFF->>MB: POST .../availability/package-slate { packageId, location, rrule }
    MB-->>BFF: { status: "OK", primarySlate: { slateId, slots[] } }
    BFF->>MB: POST .../orders { PACKAGE item }
    MB-->>BFF: { data: { order: { orderId }, items: [{ orderItemId }] } }
    BFF->>MB: POST .../orders/{orderId}/package-bookings { orderItemId, idempotencyKey, slateId }
    MB-->>BFF: { created: [...8 bookings], quantityRemaining: 0 }
    BFF-->>B: Package booked
```

> [!NOTE]
>
> **The API doesn't require payment, but a client flow must.** Credits exist
> the moment the order is created, not when it's paid, so this route books all
> N sessions from a `DRAFT` order. That suits a business booking on a client's
> behalf. When the client books their own package credits, book only from an
> order whose `status` reads `PAID`. Check it yourself before calling this
> route, because it won't refuse an unpaid order. Or use the
> [client-plane route](https://docs.gomarketbox.com/guides/book-a-package-credit.md), which refuses unpaid
> credits for you. Single bookings don't need a `PAID` order in either flow.
> A `CANCELLED` order books nothing. See
> [A cancelled order books nothing](#a-cancelled-order-books-nothing).

**1. Find the package**

A **package** is a sellable bundle — a name, a `creditCount`, and `pricing`.
List every one on a service with
`GET /services/{serviceId}/packages?status=ACTIVE`. This is the discovery
call: it spans **all of the service's offerings**, so you can make it before
the client has chosen an option, and each package carries its `offeringId`
so you can join it against the offerings list you already hold.

```ts theme={null}
// app/api/bff/packages/route.ts
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const serviceId = new URL(request.url).searchParams.get('serviceId')!;

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/services/${serviceId}/packages?status=ACTIVE`,
    {
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
      },
    },
  );

  const body = await res.json().catch(() => ({}));
  return NextResponse.json(body, { status: res.status });
}
```

The standard list envelope, one entry per bundle (abridged to two of the
service's packages):

```json theme={null}
{
  "data": [
    {
      "packageId": "pkg_01kvr4cgb3esg8hxx32kwhre7g",
      "serviceId": "srv_01kv60qg12e82acr78edfnjhvv",
      "offeringId": "off_01kv60qge5eh59ap0gw0pqrrys",
      "name": { "en": "8-Session Pack" },
      "creditCount": 8,
      "capacity": 1,
      "pricingModel": "FLAT",
      "pricing": [
        {
          "ruleId": "r_9f2c1b04",
          "scope": "DEFAULT",
          "price": { "amount": 45000, "currency": "USD" }
        },
        {
          "ruleId": "r_210b02de",
          "scope": "COUNTRY",
          "country": "CA",
          "price": { "amount": 45000, "currency": "CAD" }
        }
      ],
      "status": "ACTIVE"
    },
    {
      "packageId": "pkg_01kvc5m1t8h2y4nq7wzb3jde6k",
      "offeringId": "off_01kv60qge5eh59ap0gw0pqrrys",
      "name": { "en": "5-Session Pack" },
      "creditCount": 5,
      "status": "ACTIVE"
    }
  ],
  "nextCursor": null
}
```

> [!NOTE]
>
> **Don't list business models and render them as packages.** The
> `PACKAGE` **business model** is only a flag on the service meaning
> "this service *can* be sold as packages." It is **not** a sellable bundle,
> and it carries **no `creditCount` and no `pricing`** — those fields live on
> the packages this endpoint returns. Reading the business-models list and
> rendering each row as a package gives you one package-shaped object with
> null session count and null price, and hides the real bundles entirely.
> The packages are here; the business model just permits them.

> [!NOTE]
>
> **A service with no packages is a `200` with `data: []`, not an error** —
> hide the tab, don't branch on a status code. An **unknown** `serviceId` is a
> `404`, so a typo can never masquerade as "this service sells no packages."
> Valid `status` values are `DRAFT`, `ACTIVE`, and `ARCHIVED` — there is no
> `INACTIVE`.

Take the `packageId` of the bundle the client picks into the next step.

**2. Build the slate**

Call `POST /availability/package-slate` with the package, a location, a
timezone, and a bounded recurrence rule. The example below uses the
travel-zone branch (`lat` + `lng` + `address`) — you can pass a stored
`locationId` instead if you have one.

```ts theme={null}
// app/api/bff/package-slate/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { packageId } = await request.json();

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/availability/package-slate`,
    {
      method: 'POST',
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        packageId,
        lat: 43.6532,
        lng: -79.3832,
        address: {
          addressOneLine: '100 Queen St W, Toronto, ON M5H 2N2, Canada',
          streetNumber: '100',
          streetName: 'Queen St W',
          city: 'Toronto',
          state: 'ON',
          country: 'CA',
          zipCode: 'M5H 2N2',
        },
        timezone: 'America/Toronto',
        lookAheadStartDate: '2026-07-09T00:00:00-04:00',
        rrule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;COUNT=8',
      }),
    },
  );

  const body = await res.json().catch(() => ({}));
  return NextResponse.json(body, { status: res.status });
}
```

> [!WARNING]
>
> `lookAheadStartDate` must carry a **numeric `±HH:MM` offset** (e.g.
> `-04:00`) — a `Z` suffix is rejected. That offset must also match the
> timezone's **actual UTC offset for that date, including daylight saving** —
> Toronto is `-04:00` in summer (EDT) but `-05:00` in winter (EST), so a
> copy-pasted `-04:00` will be wrong off-season. `timezone` must be an **IANA
> identifier** (`America/Toronto`, never `EST`). `rrule` must include a
> **bounded, positive `COUNT`** (e.g. `COUNT=8`) — an unbounded rrule almost
> always returns nothing bookable. All three are enforced request-shape
> validation (`400`), not just convention.

A successful response carries `status: "OK"` and the `primarySlate` — the
`sessionsFilled` out of `sessionsRequested`, plus the resolved `slots[]`
(shown here abridged to the first slot of 8):

```json theme={null}
{
  "status": "OK",
  "reason": null,
  "suggestionRequestId": "sugreq_01kx16ej7pe4r9da74adf6m4h0",
  "resolvableUntil": "2026-07-10T00:00:00.000Z",
  "primarySlate": {
    "slateId": "slate_01kx16ejsqffc9rbgdcc591w2p",
    "supplierId": "sup_01kv60qgnef2kt3pvqgwmkbzfr",
    "completeness": "COMPLETE",
    "sessionsRequested": 8,
    "sessionsFilled": 8,
    "startTimeConsistencyPercent": 100,
    "matchScore": 1,
    "matchComponents": { "startDate": 1, "cadence": 1 },
    "totalTravelTimeMins": 0,
    "slots": [
      {
        "slotId": "slot_01kx16ejsrfs7tf3edy19wdsf8",
        "sessionIndex": 1,
        "supplierId": "sup_01kv60qgnef2kt3pvqgwmkbzfr",
        "serviceId": "srv_01kv60qg12e82acr78edfnjhvv",
        "offeringId": "off_01kv60qge5eh59ap0gw0pqrrys",
        "bookingStartUtc": "2026-07-09T13:30:00.000Z",
        "bookingEndUtc": "2026-07-09T14:00:00.000Z",
        "bookingTz": "America/Toronto",
        "locationType": "TRAVEL_ZONE",
        "locationId": "stz_01kv60qgs4e4nbjhzradnqtj0h",
        "latitude": 43.6532,
        "longitude": -79.3832,
        "reservationStatus": "FREE"
      }
    ]
  },
  "alternates": [],
  "partial": null
}
```

> [!NOTE]
>
> If nothing bookable can be found, the response is `422` with `code:
>       "NO_COMPLETE_SLATE"` (a complete single-supplier plan doesn't exist under
> the project's supplier policy) or `code: "NO_AVAILABILITY"` (no availability
> at all in the window). See the Reference section below.

`matchScore` is the mean of `matchComponents` — here `1`, since session one
lands on the window's first day and the plan runs at exactly the requested
cadence. See [How well a slate matches](https://docs.gomarketbox.com/resources/suggestions.md#how-well-a-slate-matches-matchscore-and-matchcomponents)
for the full breakdown and how ranking works.

You only need `primarySlate.slateId` for the next steps — hold onto it.

**3. Create the order**

Create an order with one `PACKAGE` item naming the package. You don't send
the service, offering, session count, or price — the server derives all of
them from the package definition. You **do** need to tell the order where
this booking happens, or it prices off the client's default saved address
(or the package's `DEFAULT` rule) instead of the region you quoted. This guide's flow never holds the slate (holding is
covered separately, below), so the region source it actually has on hand at
this point is the same `address` (or `locationId`) passed to
`POST /availability/package-slate` in Step 2 — pass that:

```ts theme={null}
// app/api/bff/orders/route.ts
import { NextResponse } from 'next/server';
import { signedInClientId } from '@/lib/client'; // see Create a single booking

export async function POST(request: Request) {
  const clientId = await signedInClientId(request); // never from the request body
  const { packageId } = await request.json();

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/orders`,
    {
      method: 'POST',
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        clientId,
        currency: 'CAD',
        // Same address passed to package-slate in Step 2 — this is what
        // selects the CAD price. Booking a stored Location instead of a
        // travel zone? Pass that Location's locationId here instead.
        address: {
          addressOneLine: '100 Queen St W, Toronto, ON M5H 2N2, Canada',
          streetNumber: '100',
          streetName: 'Queen St W',
          city: 'Toronto',
          state: 'ON',
          country: 'CA',
          zipCode: 'M5H 2N2',
        },
        items: [{ skuType: 'PACKAGE', packageId }],
      }),
    },
  );

  const body = await res.json().catch(() => ({}));
  return NextResponse.json(body, { status: res.status });
}
```

> [!TIP]
>
> **Holding the slate first (see [Hold slots during checkout](https://docs.gomarketbox.com/guides/hold-slots-for-checkout.md))?
> Pass `reservationId` instead — it's the preferred region source when you have
> it**, since the hold is the same record the eventual bookings are rebuilt
> from, so the order can't disagree with them on price:
>
> ```ts theme={null}
> body: JSON.stringify({
>   clientId,
>   currency: 'CAD',
>   reservationId,          // the hold — this is what selects the CAD price
>   items: [{ skuType: 'PACKAGE', packageId }],
> }),
> ```
>
> `reservationId` takes priority over `locationId`/`address` if you send more
> than one — see [Regional pricing](https://docs.gomarketbox.com/concepts/regional-pricing.md) for the full
> priority order.

> [!WARNING]
>
> **Without `reservationId`, `locationId`, or `address`, the order prices off
> the client's default saved address** (or their first saved address, if no
> default is set). Only a client with no saved address at all prices at the
> package's `DEFAULT` rule. Either way, the price and currency may differ from
> the regional price you displayed on the storefront. If you get `Package
>       currency X does not match order currency Y`, that's what happened: you told
> the order what currency you quoted, but not *where* the booking happens, so
> it resolved a different regional rule. See
> [Regional pricing](https://docs.gomarketbox.com/concepts/regional-pricing.md).

Same response shape as a single-session order — the order under `data.order`,
the item(s) under `data.items[]`. For a `PACKAGE` item, `quantity` and
`quantityRemaining` start equal to the package's `creditCount`:

```json theme={null}
{
  "data": {
    "order": {
      "orderId": "ord_01kx16f0a1c7b2sd91xzq3mn5p",
      "status": "DRAFT",
      "total": { "amount": 45000, "currency": "CAD" }
    },
    "items": [
      {
        "orderItemId": "oi_01kx16f0a1d8c3se02yzq4mn6q",
        "skuType": "PACKAGE",
        "quantity": 8,
        "quantityRemaining": 8,
        "expiresAt": "2026-10-06T00:00:00.000Z"
      }
    ]
  }
}
```

> [!WARNING]
>
> Same nesting as single bookings: the order id is at `data.order.orderId`,
> **not** `data.orderId`. Read the `PACKAGE` item's `orderItemId` off
> `data.items[0].orderItemId`.

This `orderItemId` **is** the package instance — its `quantityRemaining` is
the live credit ledger every booking call decrements. Hold onto it along
with `orderId` and the `slateId` from Step 2.

**4. Book the slate**

Book all N sessions in one call by passing the `orderItemId` from Step 3,
the `slateId` from Step 2 and an `idempotencyKey` — no session details
required. Provide **exactly one** of `sessions`, `slateId`, or `slotIds`;
`slateId` is the recommended path. `idempotencyKey` is **required**: a body
without it is a `400 VALIDATION_ERROR`.

Mint the key **once per booking attempt** — for example in the browser when
the client clicks **Book** — and send the same key when you retry that
attempt. A key minted inside the handler is new on every call, so a retry
would no longer be recognised as one.

```ts theme={null}
// app/api/bff/package-bookings/route.ts
import { NextResponse } from 'next/server';

export async function POST(
  request: Request,
  ctx: { params: Promise<{ orderId: string }> },
) {
  const { orderId } = await ctx.params;
  // idempotencyKey: minted once per attempt by the caller, reused on retry.
  const { orderItemId, slateId, idempotencyKey } = await request.json();

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/orders/${orderId}/package-bookings`,
    {
      method: 'POST',
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        orderItemId,
        idempotencyKey, // same key on retry replays the same result
        atomicity: 'all_or_nothing',
        slateId,
      }),
    },
  );

  const body = await res.json().catch(() => ({}));
  return NextResponse.json(body, { status: res.status });
}
```

> [!WARNING]
>
> **This response is NOT wrapped in `{ data }`**, unlike every other endpoint
> in this API (orders, bookings, etc.). A generic `res.data` unwrap silently
> breaks here — read `created`, `failed`, and `quantityRemaining` directly off
> the response body.

A successful response returns `201` with one entry per booked session (shown
abridged to the first two of eight):

```json theme={null}
{
  "orderId": "ord_01kx16f0a1c7b2sd91xzq3mn5p",
  "orderItemId": "oi_01kx16f0a1d8c3se02yzq4mn6q",
  "packageOrderItemId": "oi_01kx16f0a1d8c3se02yzq4mn6q",
  "atomicity": "all_or_nothing",
  "created": [
    { "sessionIndex": 0, "bookingId": "bk_01kx16f2a0e5x9jv6r0c1qs7pm", "allocationId": "alloc_01kx16f2a0f6y0kw7s1d2rt8qn" },
    { "sessionIndex": 1, "bookingId": "bk_01kx16f2a0g7z1lx8t2e3su9ro", "allocationId": "alloc_01kx16f2a0h8a2my9u3f4tv0sp" }
  ],
  "failed": [],
  "quantityRemaining": 0
}
```

> [!NOTE]
>
> **At most 15 sessions per atomic call.** `all_or_nothing` books every
> session in one transaction, which caps it at 15. A larger slate is
> `422 PACKAGE_SLATE_TOO_LARGE_FOR_ATOMIC`, and nothing is booked. Use
> `atomicity: "best_effort"` (the project must enable
> `suggestionConfig.allowPartialPackages`), or book a smaller slate.

> [!TIP]
>
> **Off-by-one trap.** `sessionIndex` is **1-based** in the slate's `slots[]`
> (Step 2) but **0-based** in this `created[]` response. Slot `sessionIndex: 1`
> corresponds to booking `sessionIndex: 0` — don't compare them directly
> without adjusting.

> [!NOTE]
>
> **Stale slot.** If a chosen slot was booked by someone else (or expired)
> between building the slate and booking it, this call returns `409` with
> `{ code: "SLOT_NO_LONGER_BOOKABLE", freshSuggestions }` instead of a
> booking. Rebuild the slate (or use `freshSuggestions` directly) and retry —
> don't retry the same stale `slateId` blindly. `freshSuggestions` is planned
> from the order item you are booking: its remaining sessions, its offering and
> its expiry. So every slate in it can be booked on this order item. It is
> `null` when the item has nothing left to plan.

## What a booking call checks

`POST .../package-bookings` draws down one order item. Before it writes
anything, it checks the request against that credit.

### Every session books the credit's own offering

A `PACKAGE` order item funds sessions of **one** service and offering: the
ones it was sold with. Every service line of every session must name that
`serviceId` and `offeringId`. This applies to `slateId`, `slotIds` and
`sessions` alike. A session that mixes the item's offering with another is
refused whole, and nothing is booked:

```json theme={null}
{
  "code": "ORDER_ITEM_SERVICE_MISMATCH",
  "message": "Order item oi_01kx16f0a1d8c3se02yzq4mn6q does not match the booked service/offering",
  "statusCode": 400,
  "requestId": "6b2e9d14-3c7a-4f85-a0d1-8e4c2b7f5a39"
}
```

A slate planned for another offering can't be booked against this item. Plan
the slate from the package the item was sold from, or from the credit itself
(see [Book the sessions left on a credit](#book-the-sessions-left-on-a-credit)).

> [!WARNING]
>
> **Behaviour change (October 2026).** This call used to accept sessions of any
> offering and draw them from the credit. It now answers `400
>   ORDER_ITEM_SERVICE_MISMATCH`, the same rule `POST /bookings` applies to
> single-session credits.

### Book only what remains

Each service line uses one session of the credit. Asking for more sessions
than `quantityRemaining` is refused up front, and nothing is booked:

```json theme={null}
{
  "code": "ORDER_ITEM_QUANTITY_UNAVAILABLE",
  "message": "Requested 8 sessions but only 3 remain on the package",
  "statusCode": 400,
  "requestId": "2d8f4a61-7e3b-4c95-b0a2-9c1e5d7f3b48"
}
```

The same code as a `409` means another booking used the credits after the
check passed. Re-read `quantityRemaining` and book what is left.

A session that starts after the item's `expiresAt` is `409 PACKAGE_EXPIRED`.
With `atomicity: "all_or_nothing"` that refuses the whole call. With
`best_effort` the session is reported in `failed[]` and the rest book.

### A cancelled order books nothing

When an order is cancelled, MarketBox cancels its remaining sessions and
releases their credits. `quantityRemaining` can then look bookable, but those
credits belong to a dead order. So a `CANCELLED` order is refused on every
route that plans or books from it:

* `POST /availability/package-slate` with its `orderId` and `orderItemId`;
* `POST /orders/{orderId}/package-bookings`;
* `POST /clients/me/orders/{orderId}/package-bookings`;
* `POST /bookings` with its `orderId`;
* `POST /holds/{reservationId}/convert` with its `orderId`, even for a hold
  that already converted.

Each of them comes back with the same envelope:

```json theme={null}
{
  "code": "ORDER_CANCELLED",
  "message": "Order ord_01kx16f0a1c7b2sd91xzq3mn5p is CANCELLED",
  "statusCode": 409,
  "requestId": "8a3c6e25-1f9d-4b72-9e40-5d2b8c1a7f63"
}
```

Don't retry. Create a new order for the client. `DRAFT`, `PENDING` and `PAID`
orders book as before.

### Retry safely with `idempotencyKey`

Send a fresh `idempotencyKey` for each booking attempt, and the **same** key
when you retry that attempt:

* **A retry with the same key and the same body replays the stored `201`.**
  This holds even when the first call used the last of the credits, and even
  if the order was cancelled after the first call. A replay books nothing new
  and sends no second confirmation email.
* **The same key with a different body is `409 IDEMPOTENCY_KEY_CONFLICT`.**
  That includes a body that would be invalid on its own, such as one naming
  another offering.
* **A `slateId` or `slotIds` retry must arrive within the slate's
  `resolvableUntil` window.** After that it is refused as a stale slate, not
  replayed. Check whether the first call succeeded by reading the order's
  bookings.

> [!WARNING]
>
> **Behaviour change (October 2026).** A same-key retry after the first call
> used the last credits used to answer `400 ORDER_ITEM_QUANTITY_UNAVAILABLE`. It
> now replays the stored `201`. A reused key with a different body that is also
> invalid used to get that body's `400` or `404`. It now gets `409
>   IDEMPOTENCY_KEY_CONFLICT`.

## Book the sessions left on a credit

A client who already owns a credit may want to book what is left on it: the
rest of a package after a cancellation returned some sessions, or a package
bought earlier and never scheduled. Plan the slate **from the credit** instead
of from the package. Send `orderId` and `orderItemId` in place of `packageId`:

```json theme={null}
{
  "orderId": "ord_01kx16f0a1c7b2sd91xzq3mn5p",
  "orderItemId": "oi_01kx16f0a1d8c3se02yzq4mn6q",
  "lat": 43.6532,
  "lng": -79.3832,
  "address": {
    "addressOneLine": "100 Queen St W, Toronto, ON M5H 2N2, Canada",
    "streetNumber": "100",
    "streetName": "Queen St W",
    "city": "Toronto",
    "state": "ON",
    "country": "CA",
    "zipCode": "M5H 2N2"
  },
  "timezone": "America/Toronto",
  "lookAheadStartDate": "2026-08-03T00:00:00-04:00",
  "rrule": "FREQ=WEEKLY;BYDAY=MO,WE;COUNT=8"
}
```

A credit plans differently from a package:

* **It plans the sessions that remain.** The `rrule`'s `COUNT` is replaced by
  the item's `quantityRemaining`. A package replaces it with its
  `creditCount`.
* **It plans the credit's own service and offering**, so the slate always
  passes the [offering check](#every-session-books-the-credit’s-own-offering).
* **The plan ends at the credit's `expiresAt`.** No slot starts at or after
  it. When the window comes from the cadence (no `lookAheadDays` or `endDate`)
  and you ask for no relaxation, a credit that expires before its sessions fit
  is `422 NO_COMPLETE_SLATE`, and `reason` names the expiry. When you size the
  window yourself, or opt in to relaxation, the window is cut at the expiry,
  and too early an expiry gives the generic `NO_COMPLETE_SLATE`.
* **It works after the package was edited or deleted.** The order item keeps
  what it was sold with.

Send **exactly one** source: `packageId`, or `orderId` with `orderItemId`.
Neither, both, or `orderId` without `orderItemId` is a `400
VALIDATION_ERROR`.

To have MarketBox confirm the credit is the client's, add their `clientId`
beside `orderId` and `orderItemId`. An order that belongs to another client is
then refused exactly like an order that doesn't exist: `400
INVALID_ORDER_REFERENCE`, and nothing is planned. Without `clientId`, the order
is not checked against a client. `clientId` beside `packageId` is a `400
VALIDATION_ERROR`.

Book the result with `POST /orders/{orderId}/package-bookings` and
`{ orderItemId, idempotencyKey, slateId }`, as in Step 4. When the signed-in client books
their own credit from your site, use the client-plane route instead. See
[Book a client's package credit](https://docs.gomarketbox.com/guides/book-a-package-credit.md).

A credit that can't be planned is refused before anything is searched:

| Credit | Status and `code` | `message` |
| - | - | - |
| The order doesn't exist in this project, or belongs to another client than `clientId` | `400 INVALID_ORDER_REFERENCE` | `Order ord_… not found` |
| The order is `CANCELLED` | `409 ORDER_CANCELLED` | `Order ord_… is CANCELLED` |
| The item doesn't exist on that order | `404 NOT_FOUND` | `Order item oi_… not found` |
| The item isn't a `PACKAGE` line | `400 NOT_A_PACKAGE_ITEM` | `Order item oi_… is not a package credit` |
| No sessions remain | `409 ORDER_ITEM_QUANTITY_UNAVAILABLE` | `Order item oi_… has no sessions remaining` |
| `expiresAt` has passed | `409 PACKAGE_EXPIRED` | `Order item oi_… expired at 2026-10-06T00:00:00.000Z` |

An expired credit, for example, comes back as:

```json theme={null}
{
  "code": "PACKAGE_EXPIRED",
  "message": "Order item oi_01kx16f0a1d8c3se02yzq4mn6q expired at 2026-10-06T00:00:00.000Z",
  "statusCode": 409,
  "requestId": "4e7a1c93-6d2f-4b58-8a05-3f9c6e2d1b74"
}
```

### Advanced: book explicit sessions

Book-by-`slateId` above is the recommended path for almost every
integration. Two more advanced paths exist for cases where you need more
control:

* **Transcribe explicit sessions.** Instead of sending `slateId`, copy every
  resolved slot from the slate response into a `sessions[]` array yourself.
  This is the fallback path — use it only if you must alter or filter
  individual sessions, and copy each slot **verbatim** (don't re-derive
  locations).
* **Hold, then convert.** Reserve the slate's supplier time while the
  client pays, then convert the hold into confirmed bookings on payment
  success — the pattern you want for a timed checkout. `POST /holds { slateId }` → `POST /holds/{reservationId}/convert`. Full walkthrough in
  [Hold slots during checkout](https://docs.gomarketbox.com/guides/hold-slots-for-checkout.md).
  Holding by `slateId` (or `slotIds`) needs **no location fields at all** —
  the slate's slots already carry the timezone, location type, location and
  address, and the hold copies them onto the reservation. Only the explicit
  `intervals` form makes you supply them.

Transcribing sessions is covered in depth in the
[availability and slates guide](https://docs.gomarketbox.com/guides/availability-and-slates.md), along with
building single one-off slots and full stale-slot recovery.

> [!WARNING]
>
> If you hold a slate, you must **convert** it — `POST .../package-bookings`
> will not consume your own hold and returns `409 SLOT_HELD` naming the
> `reservationId` you created. See
> [Concurrency](https://docs.gomarketbox.com/concepts/concurrency.md).

## Reference

### Endpoints used in this guide

| Endpoint | Method | Auth | Description |
| - | - | - | - |
| `/v1/projects/{projectId}/services/{serviceId}/packages` | `GET` | `x-api-key` | List every package on the service, across all its offerings. `?status=ACTIVE` for the purchasable bundles. `200 []` when the service sells none; `404` for an unknown `serviceId`. |
| `/v1/projects/{projectId}/availability/package-slate` | `POST` | `x-api-key` | Build an N-session slate from one supplier, for a package (`packageId`) or for what is left on a credit (`orderId` + `orderItemId`). Returns `primarySlate.slateId`. `422` when nothing is bookable. |
| `/v1/projects/{projectId}/orders` | `POST` | `x-api-key` | Create the order and its `PACKAGE` item. Order id nested at `data.order.orderId`; item at `data.items[]`. |
| `/v1/projects/{projectId}/orders/{orderId}/package-bookings` | `POST` | `x-api-key` | Book all N sessions of the slate atomically (or best-effort). Response is **not** wrapped in `{ data }`. |
| `/v1/projects/{projectId}/clients/me/orders/{orderId}/package-bookings` | `POST` | `x-api-key` + `Bearer` | The same booking, made by the signed-in client on their own credit. See [Book a client's package credit](https://docs.gomarketbox.com/guides/book-a-package-credit.md). |

### Configuration

| Value | Env var | Browser? |
| - | - | - |
| API key | `MARKETBOX_API_KEY` | **No** (server-only) |
| API base URL | `MARKETBOX_API_URL` | **No** (BFF-only) |
| Project id | `MARKETBOX_PROJECT_ID` | **No** (BFF-only) |

### Errors and edge cases

| Scenario | `code` | Status | Resolution |
| - | - | - | - |
| The service exists but sells no packages | — | `200` | Not an error: `data` is `[]`. Hide the packages tab rather than branching on a status code. |
| Unknown `serviceId` on the package list | `NOT_FOUND` | `404` | A typo never reads as "no packages" — check the id came from this project's service catalogue. |
| No complete slate for the request under the project's supplier policy | `NO_COMPLETE_SLATE` | `422` | Widen the `rrule`/`lookAheadStartDate` window, try a different location, or ask the project to enable `suggestionConfig.allowPartialPackages` if a partial plan is acceptable. |
| No availability at all in the requested window | `NO_AVAILABILITY` | `422` | Try a different location, timezone, or a later `lookAheadStartDate`. |
| `lookAheadStartDate` has a `Z` suffix instead of a numeric offset | `VALIDATION_ERROR` | `400` | Use a numeric `±HH:MM` offset, e.g. `-04:00`. |
| `timezone` or `bookingTz` is an abbreviation or offset (`EST`, `GMT+5`) rather than an IANA identifier | `VALIDATION_ERROR` | `400` | Send an IANA zone, e.g. `America/Toronto`. See [Timezones](https://docs.gomarketbox.com/concepts/timezones.md#valid-timezones). |
| `rrule` has no bounded `COUNT` | `VALIDATION_ERROR` | `400` | Add a positive `COUNT`, e.g. `FREQ=WEEKLY;BYDAY=MO;COUNT=8`. |
| Provided more than one (or none) of `sessions` / `slateId` / `slotIds` | `VALIDATION_ERROR` | `400` | Provide exactly one booking source — `slateId` for the primary flow. |
| Chosen slot went stale between building and booking | `SLOT_NO_LONGER_BOOKABLE` | `409` | The response includes `freshSuggestions` — rebuild from it and retry. |
| More than 15 sessions with `atomicity: "all_or_nothing"` | `PACKAGE_SLATE_TOO_LARGE_FOR_ATOMIC` | `422` | Use `atomicity: "best_effort"` (requires the project to enable `allowPartialPackages`), or book a smaller slate. |
| `best_effort` requested but the project hasn't enabled it | `BEST_EFFORT_NOT_ENABLED` | `422` | Stay with `all_or_nothing` (≤15 sessions), or ask the project to enable `suggestionConfig.allowPartialPackages`. |
| The supplier's time is already claimed by a live hold (often your own — you held, then booked directly instead of converting) | `SLOT_HELD` | `409` | The first `conflicts[]` entry with `claimType: "HOLD"` names the hold in `reservationId`. Convert it: [Hold slots during checkout](https://docs.gomarketbox.com/guides/hold-slots-for-checkout.md#handling-a-held-slot). |
| The supplier's time is already claimed by a confirmed booking | `SLOT_BOOKED` | `409` | Rebuild the slate and book a different time. |
| Heavy concurrent writes on one supplier-day exhausted the internal retry | `OCCUPANCY_CONTENTION` | `409` | Transient — retry the same request after a short backoff. |
| Same `idempotencyKey` reused with a different request body — even one that would be invalid on its own | `IDEMPOTENCY_KEY_CONFLICT` | `409` | Generate a fresh `idempotencyKey` per distinct booking attempt; reusing the same key with the same body safely replays the original `201`, even after the credits ran out. See [Retry safely](#retry-safely-with-idempotencykey). |
| A session starts after the order item's `expiresAt` | `PACKAGE_EXPIRED` | `409` | No session can be booked past the expiry. `all_or_nothing` refuses the whole call; `best_effort` lists the session in `failed[]`. |
| A session names a service or offering other than the order item's | `ORDER_ITEM_SERVICE_MISMATCH` | `400` | Book the item's own offering. Plan the slate from that package or from the credit. See [Every session books the credit's own offering](#every-session-books-the-credit’s-own-offering). |
| The order is `CANCELLED` | `ORDER_CANCELLED` | `409` | Its credits were released when it was cancelled. Don't retry; create a new order. Also returned by `package-slate` for a credit on that order. |
| Requested more sessions than the order item has remaining | `ORDER_ITEM_QUANTITY_UNAVAILABLE` | `400` | The up-front precheck rejects this. Check `quantityRemaining` before booking. |
| A concurrent draw-down consumed the credits mid-transaction | `ORDER_ITEM_QUANTITY_UNAVAILABLE` | `409` | A race with another booking exhausted the item after the precheck. Re-fetch `quantityRemaining` and retry with what's left. |
| `orderItemId` isn't a `PACKAGE` item | `NOT_A_PACKAGE_ITEM` | `400` | Pass the `orderItemId` of the `PACKAGE` item from Step 3, not a `SINGLE_SESSION` item. |
| `orderId` doesn't exist, or belongs to another project | `INVALID_ORDER_REFERENCE` | `400` | Double-check the `orderId` came from a `POST /orders` call in the same project. |
| `orderItemId` doesn't exist on that order | `NOT_FOUND` | `404` | Re-fetch the order aggregate — you may be reusing a stale id. |
| A session's `locationId` names no Location or travel zone in this project | `NOT_FOUND` | `404` | Take the id from the slate, or from `GET /locations`. |
| A session's location is the wrong type, or another supplier's travel zone | `BAD_REQUEST` | `400` | `message` names the id. Book from the slate, which carries the right location. |
| A session's `PHYSICAL` Location has no coordinates | `UNPROCESSABLE_ENTITY` | `422` | The business fixes the Location. Don't retry. |
| The package's offering has no `DEFAULT` price rule | `OFFERING_NOT_PRICED` | `422` | The business adds one. Don't retry. |
| A session's offering isn't `ACTIVE` | `NOT_SELLABLE` | `422` | "Offering off\_… is INACTIVE and is not sold; only ACTIVE offerings take new bookings and orders". A credit already bought stays bookable when its service stops being `LIVE`, but not when its offering is deactivated. Don't retry. |
| On order create: the service isn't `LIVE` or was deleted, or the offering isn't `ACTIVE` | `NOT_SELLABLE` | `422` | `message` names the id and its status. Sell another service or offering. Don't retry. |
| `package-slate` with neither `packageId` nor `orderId` + `orderItemId`, or with both | `VALIDATION_ERROR` | `400` | Send exactly one source. |
| `package-slate` for a credit with no sessions left | `ORDER_ITEM_QUANTITY_UNAVAILABLE` | `409` | Nothing to plan. The credit is used up. |
| `package-slate` for a credit whose `expiresAt` has passed | `PACKAGE_EXPIRED` | `409` | Nothing can be planned on it. |

See [Errors](https://docs.gomarketbox.com/concepts/errors.md) for the full envelope and code list.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.