> ## 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 single booking

> Book one client into one session — create an order, find its order item, then create the booking that draws it down.

This guide walks through the single-session booking flow end to end: create
an order, read the order item it produced, then create the booking that
consumes it. For a client checkout that also holds the time and takes
payment, start from [Client checkout, end to end](https://docs.gomarketbox.com/guides/client-checkout-end-to-end.md).

It builds on [The booking engine model](https://docs.gomarketbox.com/concepts/booking-engine-model.md) —
read that first if you haven't. The one rule to keep in mind here: **you
can't create a booking without an order item to draw down.** For a single
session, that means one order with one `SINGLE_SESSION` item, funding exactly
one booking. 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.

## How it works

A single booking is three calls, always in this order:

1. **Create the order** with one `SINGLE_SESSION` item. This is what makes
   the session purchasable — it's the order item the booking will draw down.
2. **Read the order item's id.** The order-create response already includes
   it, but if the booking step runs later or in a different request, look it
   up again with the aggregate endpoint.
3. **Create the booking**, with the service line carrying
   `businessModelType: "SINGLE_BOOKING"` plus the `orderId` and `orderItemId`
   from steps 1–2.

```mermaid theme={null}
sequenceDiagram
    participant B as Browser
    participant BFF as Your BFF
    participant MB as MarketBox API
    B->>BFF: Book this session
    BFF->>MB: POST .../orders { SINGLE_SESSION item }
    MB-->>BFF: { data: { order: { orderId }, items: [{ orderItemId }] } }
    BFF->>MB: GET .../orders/{orderId}/aggregate
    MB-->>BFF: { data: { order, items } }
    BFF->>MB: POST .../bookings { orderId, orderItemId, ... }
    MB-->>BFF: { data: { bookingId, status: "SCHEDULED" } }
    BFF-->>B: Booking confirmed
```

> [!NOTE]
>
> **Payment is not required.** Credits exist the moment the order is created,
> not when it's paid. The order stays `DRAFT` and the booking still succeeds —
> don't gate booking on Stripe. Layer payment on afterward with
> [Accept payments with Stripe](https://docs.gomarketbox.com/guides/accept-payments-with-stripe.md).
> A `CANCELLED` order books nothing: `409 ORDER_CANCELLED`.

> [!NOTE]
>
> **`POST /bookings` books immediately — there's no reservation window.** To
> reserve this supplier's time while the client pays, hold it first:
> `POST /holds { intervals: [...] }`, then convert the hold into this same
> booking on payment success. A single session can be held on its own — no
> package, no slate. Each held interval takes the **same location fields as
> the booking body below** (`bookingTz` and `locationType` are required, and
> `locationType` decides the rest) — the hold is what convert rebuilds the
> booking from. See
> [Hold slots during checkout](https://docs.gomarketbox.com/guides/hold-slots-for-checkout.md).
>
> If you *do* hold the time, you must convert it: this route will not consume
> your hold and returns `409 SLOT_HELD` naming the `reservationId` you
> created.

**1. Create the order**

Create an order with a single `SINGLE_SESSION` item naming the service and
offering being booked. You don't send a price — the server prices the item
from the offering itself. You **do** need to tell the order where this
session happens: this example books a `TRAVEL_ZONE` session (Step 3 below),
so it passes the client's service `address` — the same one the booking call
uses. Booking a `PHYSICAL` session instead? Pass that Location's
`locationId` here rather than `address`. See
[Regional pricing](https://docs.gomarketbox.com/concepts/regional-pricing.md) for the full priority order
(`reservationId` → `locationId` → `address`) and why it matters.

Resolve the client's `clientId` on the server. Never trust a `clientId` the
browser sends: anyone can put another client's id in a request body. For a
signed-in client, `POST /clients/me` with their token returns it (see
[Onboard the client](https://docs.gomarketbox.com/guides/booking-flow-auth.md#onboard-the-client)):

```ts theme={null}
// lib/client.ts — shared by the BFF routes below
export async function signedInClientId(request: Request): Promise<string> {
  const authorization = request.headers.get('authorization'); // the client's Bearer token
  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/clients/me`,
    {
      method: 'POST',
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
        ...(authorization && { authorization }),
      },
    },
  );
  if (!res.ok) throw Object.assign(new Error('client lookup failed'), { status: res.status });
  return (await res.json()).data.clientId as string;
}
```

Booking on a client's behalf with no client signed in? Take the `clientId`
from your own records on the server instead.

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

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

  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',
        address: {                      // the session's address — selects the CAD price
          addressOneLine: '123 Queen St W, Toronto, ON M5H 2M9, Canada',
          streetNumber: '123',
          streetName: 'Queen St W',
          city: 'Toronto',
          state: 'ON',
          country: 'CA',
          zipCode: 'M5H 2M9',
        },
        items: [
          {
            skuType: 'SINGLE_SESSION',
            serviceId: 'srv_01kv60qg12e82acr78edfnjhvv',
            offeringId: 'off_01kv60qge5eh59ap0gw0pqrrys',
            quantity: 1,
          },
        ],
      }),
    },
  );

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

> [!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
> offering's `DEFAULT` rule. Either way, the price and currency may differ
> from the regional price you displayed. If you get `Item currency X does not
>       match order currency Y`, that's what happened: you told the order what
> currency you quoted, but not *where* the session happens, so it resolved a
> different regional rule. See [Regional pricing](https://docs.gomarketbox.com/concepts/regional-pricing.md).

The response nests the order under `order`, not at the top level:

```json theme={null}
{
  "data": {
    "order": {
      "orderId": "ord_01kx16ek2jf4r9da74adf6m4h0",
      "status": "DRAFT",
      "total": { "amount": 4000, "currency": "CAD" }
    },
    "items": [
      {
        "orderItemId": "oi_01kx16ek2kf2fsc9x7b2n1dfc9",
        "skuType": "SINGLE_SESSION",
        "quantity": 1,
        "quantityRemaining": 1,
        "unitPrice": { "amount": 4000, "currency": "CAD" }
      }
    ],
    "summary": { "total": { "amount": 4000, "currency": "CAD" }, "amountDue": { "amount": 4000, "currency": "CAD" } }
  }
}
```

> [!WARNING]
>
> The order id is at `data.order.orderId`, **not** `data.orderId`. This trips
> up naive `res.data.orderId` unwrapping — every order response is shaped
> `{ order, items, summary }`.

**2. Get the order item id**

You already have `orderItemId` from the create response above — for a
single, immediate checkout you can skip straight to Step 3. If the booking
step happens later, or in a separate request that only has the `orderId`,
fetch it again with the aggregate endpoint:

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

export async function GET(
  _req: Request,
  ctx: { params: Promise<{ orderId: string }> },
) {
  const { orderId } = await ctx.params;

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/orders/${orderId}/aggregate`,
    { headers: { 'x-api-key': process.env.MARKETBOX_API_KEY! } },
  );

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

Same shape as the create response — `data.order` plus `data.items[]`. Read
the `SINGLE_SESSION` item's `orderItemId` off `data.items[0].orderItemId`.

**3. Create the booking**

Create the booking. The service line carries `businessModelType:
    "SINGLE_BOOKING"` plus the `orderId`/`orderItemId` pair from steps 1–2 — this
is what ties the schedule entry back to the order item it draws down. The
example below uses `locationType: "TRAVEL_ZONE"`, which needs the most
fields; see the location rules warning below for `PHYSICAL` and `VIRTUAL`.

```ts theme={null}
// app/api/bff/bookings/route.ts
import { NextResponse } from 'next/server';
import { signedInClientId } from '@/lib/client';

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

  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${process.env.MARKETBOX_PROJECT_ID}/bookings`,
    {
      method: 'POST',
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        clientId,
        supplierId: 'sup_01kv60qgnef2kt3pvqgwmkbzfr',
        bookingStartUtc: '2026-07-09T13:30:00.000Z',
        bookingEndUtc: '2026-07-09T14:00:00.000Z',
        bookingTz: 'America/Toronto',
        locationType: 'TRAVEL_ZONE',
        locationId: 'stz_01kv60qgs4e4nbjhzradnqtj0h', // supplierTravelZoneId
        latitude: 43.6532,
        longitude: -79.3832,
        address: {
          addressOneLine: '123 Queen St W, Toronto, ON M5H 2M9, Canada',
          streetNumber: '123',
          streetName: 'Queen St W',
          city: 'Toronto',
          state: 'ON',
          country: 'CA',
          zipCode: 'M5H 2M9',
        },
        capacity: 1,
        services: [
          {
            serviceId: 'srv_01kv60qg12e82acr78edfnjhvv',
            offeringId: 'off_01kv60qge5eh59ap0gw0pqrrys',
            businessModelType: 'SINGLE_BOOKING',
            quantity: 1,
            orderId,
            orderItemId,
          },
        ],
      }),
    },
  );

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

A successful response returns the created booking, `status: "SCHEDULED"`:

```json theme={null}
{
  "data": {
    "bookingId": "bk_01kx16f2a0e5x9jv6r0c1qs7pm",
    "status": "SCHEDULED",
    "supplierId": "sup_01kv60qgnef2kt3pvqgwmkbzfr",
    "clientId": "cli_dolphin_web",
    "bookingStartUtc": "2026-07-09T13:30:00.000Z",
    "bookingEndUtc": "2026-07-09T14:00:00.000Z",
    "bookingLocalDate": "2026-07-09",
    "bookingLocalStartTime": "09:30:00"
  }
}
```

> [!NOTE]
>
> The `bookingLocal*` fields are computed server-side from `bookingTz` — never
> send them yourself. Times are `HH:mm:ss`. See [Timezones](https://docs.gomarketbox.com/concepts/timezones.md).
>
> The booking response doesn't echo the service lines. Read them from
> `GET /bookings/{bookingId}/aggregate`.

> [!WARNING]
>
> **Location fields depend on `locationType`** — the API rejects the wrong
> combination with a `400`:
>
> | `locationType` | Required alongside it | Must be omitted or `null` |
> | - | - | - |
> | `VIRTUAL` | nothing | `locationId`, `latitude`, `longitude` |
> | `PHYSICAL` | `locationId` — a **Location** id (`loc_…`) | `latitude`, `longitude` (derived from the Location) |
> | `TRAVEL_ZONE` | `locationId` — the **`supplierTravelZoneId`** (`stz_…`) — plus `latitude`, `longitude` and a structured `address` | — |
>
> The `address` object (`addressOneLine`, `streetNumber`, `streetName`, `city`,
> `state`, `country` as ISO-2, `zipCode`, plus optional `unitNumber`) is
> required on every `TRAVEL_ZONE` booking — there's no fallback that derives it
> for you on the single-booking path.

## Reference

### Endpoints used in this guide

| Endpoint | Method | Auth | Description |
| - | - | - | - |
| `/v1/projects/{projectId}/clients/me` | `POST` | `x-api-key` + `Bearer` | Resolve the signed-in client's `clientId` on the server. |
| `/v1/projects/{projectId}/orders` | `POST` | `x-api-key` | Create the order and its `SINGLE_SESSION` item. Order id is nested at `data.order.orderId`. |
| `/v1/projects/{projectId}/orders/{orderId}/aggregate` | `GET` | `x-api-key` | Read the order plus its items — use this to (re)fetch `orderItemId`. |
| `/v1/projects/{projectId}/bookings` | `POST` | `x-api-key` | Create the booking. Each service line must reference an existing `orderId` + `orderItemId`. |

### 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 |
| - | - | - | - |
| `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 | `INVALID_ORDER_ITEM_REFERENCE` | `400` | Re-fetch the order aggregate — you may be reusing a stale id. |
| `orderItemId`'s service/offering doesn't match the booking's service line | `ORDER_ITEM_SERVICE_MISMATCH` | `400` | The `serviceId`/`offeringId` on the booking's service line must match the order item that funded it. |
| The service line's `businessModelType` isn't what the order item is sold as | `ORDER_ITEM_BUSINESS_MODEL_MISMATCH` | `400` | A `SINGLE_SESSION` item books only as `SINGLE_BOOKING`. |
| `clientId` doesn't exist in this project, on the order or the booking | `NOT_FOUND` | `404` | The message is `Client not found`. Resolve the client server-side with `POST /clients/me`. |
| The service has no active `SINGLE_BOOKING` rate, on order create | `SERVICE_NOT_SOLD_AS` | `422` | The service isn't sold as a single session. Sell an offering of a service that is, or ask the business to add the rate. |
| Order item has no quantity left to draw down | `ORDER_ITEM_QUANTITY_UNAVAILABLE` | `400` | A `SINGLE_SESSION` item only funds one booking. Create a new order for another session. |
| The order is `CANCELLED` | `ORDER_CANCELLED` | `409` | Its credits were released when it was cancelled. Don't retry; create a new order. `DRAFT`, `PENDING` and `PAID` orders book as before. |
| 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, such as "Service srv\_… is DRAFT and is not sold; only LIVE services take new bookings and orders". Sell another service or offering. Don't retry. |
| On booking create: the line'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 service that stopped being `LIVE` after the order was placed still books. Don't retry. |
| The offering has no `DEFAULT` price rule, on order create or booking create | `OFFERING_NOT_PRICED` | `422` | The business adds a `DEFAULT` rule to the offering. Don't retry. |
| `locationId` names no Location or travel zone in this project | `NOT_FOUND` | `404` | The message is `Booking location loc_… not found`. Take the id from `GET /locations` or the supplier's travel zone. |
| The location is the wrong type for `locationType`, or another supplier's travel zone | `BAD_REQUEST` | `400` | `message` names the id and the type. Send a `loc_` id for `PHYSICAL` and the supplier's own `stz_` id for `TRAVEL_ZONE`. |
| A `PHYSICAL` Location has no coordinates | `UNPROCESSABLE_ENTITY` | `422` | The business fixes the Location. Don't retry. |
| Wrong location fields for `locationType` | `VALIDATION_ERROR` | `400` | Match the table above — e.g. sending `latitude` on a `PHYSICAL` booking, or omitting `address` on `TRAVEL_ZONE`. |
| `bookingEndUtc` not after `bookingStartUtc` | `BAD_REQUEST` | `400` | Fix the time window and retry. |
| The supplier's time is claimed by a live hold — very often **your own**, if you held it and then called this route instead of converting | `SLOT_HELD` | `409` | Take the first `conflicts[]` entry with `claimType: "HOLD"`, read its `reservationId`, and call `POST /holds/{reservationId}/convert` instead. If the hold isn't yours, `heldUntil` says when it lapses. See [Hold slots during checkout](https://docs.gomarketbox.com/guides/hold-slots-for-checkout.md#handling-a-held-slot). |
| The supplier is already booked for that time | `SLOT_BOOKED` | `409` | `conflicts[0].bookingId` names the booking. Supplier time is exclusive — offer a different slot. |
| Heavy concurrent writes on one supplier-day exhausted the internal retry | `OCCUPANCY_CONTENTION` | `409` | Transient — retry the same request after a short backoff. See [Concurrency](https://docs.gomarketbox.com/concepts/concurrency.md). |

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.