Skip to content

create-cart ​

Method: POST
Path: /carts

Tags: Carts

Summary ​

Create cart

Description ​

Creates a Cart or reuses its active cart and updates the items. Reusing a cart re-applies its coupon and redeemed loyalty points against the updated contents; eligibility and retained amounts are recalculated.

Storefront SDK Usage ​

SDK Method: sdk.cart.createCart()

Example:

typescript
const { data, error, events } = await sdk.cart.createCart({
  items: [
    {
      product_id: "01H9XYZ12345ABCDE",
      variant_id: null,
      quantity: 2
    },
    {
      product_id: "01H9ABC67890FGHIJ",
      variant_id: "01H9XYZ67890KLMNO",
      quantity: 1
    }
  ],
  metadata: {
    "source": "web",
    "campaign": "summer_sale"
  }
});

if (error) {
  console.error("Failed to create cart:", error.message);
} else {
  console.log("Cart created:", data.cart.id);
  // Forward `events` to `@commercengine/analytics` so the browser and
  // server copies dedupe on their server-issued `event_id`
  console.log("Events:", events.map((event) => event.event_id));
}

TypeScript Definition ​

typescript
"create-cart": {
        parameters: {
            query?: never;
            header?: {
                /** @description A ULID you propose as the `event_id` of the first entry this request returns in `events`. Used only when it is a valid ULID minted within a day of now and not already used; otherwise the server mints one. The `event_id` returned in `events` is the one to send. */
                "X-CE-Event-ID"?: components["parameters"]["ProposedEventId"];
            };
            path?: never;
            cookie?: never;
        };
        requestBody: {
            content: {
                "application/json": {
                    items: components["schemas"]["UpdateCartItem"][];
                    /** @description Custom scalar values: strings, numbers or null. Numbers are returned as strings; blank and whitespace strings are preserved. custom_metadata may wrap the same key/value map; flat keys take precedence. Boolean, array and other nested-object values return 400. POS attribution and reserved identity keys are ignored and set from the session. */
                    metadata?: {
                        custom_metadata?: {
                            [key: string]: string | number | null;
                        } | null;
                    } & {
                        [key: string]: ((string | number | null) | {
                            [key: string]: string | number | null;
                        }) | (string | number | null);
                    };
                    /** @enum {string} */
                    fulfillment_type?: "delivery" | "collect-in-store" | "partial-collect-and-delivery";
                };
            };
        };
        responses: {
            /** @description OK */
            200: {
                headers: {
                    [name: string]: unknown;
                };
                content: {
                    "application/json": {
                        message: string;
                        success: boolean;
                        content: {
                            cart: components["schemas"]["CartRead"];
                        };
                        /** @description Analytics events to emit for the change this request made, each with a server-issued `event_id`. Replay them to your analytics destinations so your client-side and server-side copies of the same action dedupe. Empty when the request produced no analytics event. */
                        events: components["schemas"]["StorefrontResponseEvent"][];
                    };
                };
            };
            /** @description Invalid items, subscription plan, fulfillment type or metadata. Metadata values must be scalar text, numbers or null. */
            400: components["responses"]["BadRequest"];
            401: components["responses"]["Unauthorized"];
            403: components["responses"]["Forbidden"];
            /** @description The requested product does not exist. */
            404: components["responses"]["NotFound"];
            500: components["responses"]["InternalServerError"];
            504: components["responses"]["GatewayTimeout"];
        };
    };

Component References ​

ReferenceResolves To
components["parameters"]["ProposedEventId"]ProposedEventId
components["schemas"]["UpdateCartItem"]UpdateCartItem
components["schemas"]["CartRead"]CartRead
components["schemas"]["StorefrontResponseEvent"]StorefrontResponseEvent
components["responses"]["BadRequest"]BadRequest
components["responses"]["Unauthorized"]Unauthorized
components["responses"]["Forbidden"]Forbidden
components["responses"]["NotFound"]NotFound
components["responses"]["InternalServerError"]InternalServerError
components["responses"]["GatewayTimeout"]GatewayTimeout

Parameters ​

  • X-CE-Event-ID (header): A ULID you propose as the event_id of the first entry this request returns in events. Used only when it is a valid ULID minted within a day of now and not already used; otherwise the server mints one. The event_id returned in events is the one to send.

Request Body ​

Content Types: application/json

Responses ​

200 ​

OK

400 ​

Bad request

401 ​

Authentication failed. Codes include token-required, token-expired and token_not_valid for an invalid or expired token.

403 ​

Access denied. token-required requires an authenticated session; permission-denied means the caller cannot access this resource. On POS, session-expired requires signing in again.

404 ​

Requested resource not found

500 ​

The request failed because of an unexpected error.

504 ​

The request timed out.

OpenAPI Definition ​

json
{
  "tags": [
    "Carts"
  ],
  "operationId": "create-cart",
  "summary": "Create cart",
  "description": "Creates a Cart or reuses its active cart and updates the items. Reusing a cart re-applies its coupon and redeemed loyalty points against the updated contents; eligibility and retained amounts are recalculated.",
  "externalDocs": {
    "url": "https://llm-docs.commercengine.io/storefront/operations/create-cart",
    "description": "API reference for the create-cart operation"
  },
  "parameters": [
    {
      "$ref": "#/components/parameters/ProposedEventId"
    }
  ],
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": [
            "items"
          ],
          "properties": {
            "items": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/UpdateCartItem"
              }
            },
            "metadata": {
              "description": "Custom scalar values: strings, numbers or null. Numbers are returned as strings; blank and whitespace strings are preserved. custom_metadata may wrap the same key/value map; flat keys take precedence. Boolean, array and other nested-object values return 400. POS attribution and reserved identity keys are ignored and set from the session.",
              "type": "object",
              "additionalProperties": {
                "anyOf": [
                  {
                    "type": [
                      "string",
                      "number",
                      "null"
                    ]
                  },
                  {
                    "type": "object",
                    "additionalProperties": {
                      "type": [
                        "string",
                        "number",
                        "null"
                      ]
                    }
                  }
                ]
              },
              "patternProperties": {
                "^(?!custom_metadata$|pos_user_id$|pos_device_id$|origin_location_id$|sales_channel_id$|store_id$|cart_id$|id$|created_at$|modified_at$).*$": {
                  "type": [
                    "string",
                    "number",
                    "null"
                  ]
                }
              },
              "properties": {
                "custom_metadata": {
                  "type": [
                    "object",
                    "null"
                  ],
                  "additionalProperties": {
                    "type": [
                      "string",
                      "number",
                      "null"
                    ]
                  }
                }
              }
            },
            "fulfillment_type": {
              "type": "string",
              "enum": [
                "delivery",
                "collect-in-store",
                "partial-collect-and-delivery"
              ]
            }
          }
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "OK",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "required": [
              "message",
              "success",
              "content",
              "events"
            ],
            "properties": {
              "message": {
                "type": "string"
              },
              "success": {
                "type": "boolean"
              },
              "content": {
                "properties": {
                  "cart": {
                    "$ref": "#/components/schemas/CartRead"
                  }
                },
                "required": [
                  "cart"
                ],
                "type": "object"
              },
              "events": {
                "description": "Analytics events to emit for the change this request made, each with a server-issued `event_id`. Replay them to your analytics destinations so your client-side and server-side copies of the same action dedupe. Empty when the request produced no analytics event.",
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/StorefrontResponseEvent"
                }
              }
            }
          }
        }
      },
      "links": {
        "AddItemToCart": {
          "operationId": "update-cart",
          "parameters": {
            "id": "$response.body#/content/cart/id"
          },
          "description": "Add items to the newly created cart."
        },
        "SetCartAddress": {
          "operationId": "create-cart-address",
          "parameters": {
            "id": "$response.body#/content/cart/id"
          },
          "description": "Set billing and shipping address on this cart."
        },
        "SetCartFulfillment": {
          "operationId": "update-fulfillment-preference",
          "parameters": {
            "id": "$response.body#/content/cart/id"
          },
          "description": "Set the fulfillment preference on this cart."
        }
      }
    },
    "400": {
      "description": "Invalid items, subscription plan, fulfillment type or metadata. Metadata values must be scalar text, numbers or null.",
      "$ref": "#/components/responses/BadRequest"
    },
    "401": {
      "$ref": "#/components/responses/Unauthorized"
    },
    "403": {
      "$ref": "#/components/responses/Forbidden"
    },
    "404": {
      "description": "The requested product does not exist.",
      "$ref": "#/components/responses/NotFound"
    },
    "500": {
      "$ref": "#/components/responses/InternalServerError"
    },
    "504": {
      "$ref": "#/components/responses/GatewayTimeout"
    }
  },
  "security": [
    {
      "Authorization": []
    }
  ],
  "x-speakeasy-group": "carts",
  "x-speakeasy-ignore": false,
  "x-speakeasy-name-override": "createCart"
}

Auto-generated from OpenAPI spec and TypeScript definitions

Last updated: