---
id: CreateBasket
name: Create basket
version: 1.0.0
badges:
  - content: Order Lifecycle
    backgroundColor: blue
    textColor: blue
summary: Creates a basket containing the supplied item identifiers and quantities.
owners:
  - commerce-fulfillment-team
schemaPath: schema.json
operation:
  method: POST
  path: /api/v1/baskets
  statusCodes: ["201", "400"]
sidebar:
  badge: "POST"
---

`CreateBasket` creates a customer-scoped [[entity|basket]] in [[service|basket-api]] (`POST /basket/api/v1/baskets`) with an initial non-empty list of book items and quantities, returning the authenticated customer's identifier. It persists the basket directly in Redis and overwrites any existing basket for the same customer.

## Overview

| Property                           | Value                                                                                                                                                            |
| :--------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context**                | Shopping                                                                                                                                                         |
| **Owner Service**                  | [[service\|basket-api]]                                                                                                                                          |
| **Protocol / Format**              | HTTP `POST`, `application/json` request and response                                                                                                             |
| **Gateway Endpoint**               | `POST /basket/api/v1/baskets` (service path `/api/v1/baskets`)                                                                                                   |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` role plus scopes `basket_read`, `basket_write`                                                                               |
| **Idempotency / Concurrency**      | Overwrites any existing basket for the authenticated customer; no `x-request-id` header is enforced                                                              |
| **Rate Limit / Caching**           | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` tokens, `+20` per `10s`, queue `5`); stored in Redis with no TTL |
| **Contract Version**               | `1.0.0` (`ApiVersions.V1`)                                                                                                                                       |

## Request & Response Contract

### Request Body (`application/json`)

| Name               | Type       | Required | Constraints      | Description                                                   |
| :----------------- | :--------- | :------- | :--------------- | :------------------------------------------------------------ |
| `items`            | `object[]` | Yes      | Non-empty array  | Initial collection of books to store in the customer's basket |
| `items[].id`       | `string`   | Yes      | Non-empty string | Identifier of the Catalog book                                |
| `items[].quantity` | `integer`  | Yes      | `>= 1`           | Requested unit quantity for the book                          |

### Success Response (`201 Created`)

| Name              | Type     | Required | Constraints                                      | Description                                 |
| :---------------- | :------- | :------- | :----------------------------------------------- | :------------------------------------------ |
| `Location` header | `string` | Yes      | Relative path `/api/v1/baskets?id=<customer-id>` | URI to retrieve the created basket          |
| Root body         | `string` | Yes      | Derived from caller's `NameIdentifier` claim     | Authenticated customer ID owning the basket |

## Behavior & Side Effects

- **Customer scoping:** Resolves the basket owner exclusively from the JWT `NameIdentifier` claim; callers cannot supply a customer ID in the request body or route.
- **Redis storage & overwrite semantics:** Persists the basket as camelCase JSON in Redis (`basket:{userId}`) with no expiration (TTL), overwriting any existing basket for the same customer.
- **Deferred catalog enrichment:** Stores only book IDs and quantities; book titles and prices are resolved on read via [[query|GetBasket]].
- **No integration events:** HTTP basket creation does not publish any Kafka integration events.

## Error Responses

| Status / Code               | Condition                                                                                            | Client Recovery Action                                               |
| :-------------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
| `400 Bad Request`           | Missing `items`, empty `items` array, empty `items[].id`, `items[].quantity <= 0`, or malformed JSON | Fix the failing fields and resubmit                                  |
| `401 Unauthorized`          | Missing, expired, or invalid Entra ID bearer token                                                   | Acquire a valid Entra ID access token and retry                      |
| `403 Forbidden`             | Valid token missing the `customer` role or `basket_read`/`basket_write` scopes                       | Request a token with the required role and scopes                    |
| `429 Too Many Requests`     | Rate limit quota exceeded (`Retry-After` header included)                                            | Wait for the `Retry-After` interval before retrying                  |
| `500 Internal Server Error` | Redis write failed or unexpected server error (`traceId` included)                                   | Retry with exponential backoff; inspect service logs using `traceId` |

## Related Documentation

- [[service|basket-api]] — Service overview, Redis storage, and authorization policy.
- [[entity|basket]] — Basket entity model.
- [[command|UpdateBasket]] — Replace all items in an existing basket.
- [[command|DeleteBasket]] — Remove the authenticated customer's basket.
- [[query|GetBasket]] — Retrieve the current basket enriched with Catalog titles and prices.

<NodeGraph />

<SchemaViewer file="schema.json" title="Create basket schema" maxHeight="500" search="true" />


 ## Raw Schema:schema.json

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"title": "CreateBasketCommand",
	"type": "object",
	"required": ["items"],
	"properties": {
		"items": {
			"type": "array",
			"items": {
				"type": "object",
				"required": ["id", "quantity"],
				"properties": {
					"id": {
						"type": "string"
					},
					"quantity": {
						"type": ["integer", "string"],
						"format": "int32",
						"pattern": "^-?(?:0|[1-9]\\d*)$"
					}
				}
			}
		}
	}
}
