---
id: basket-api
name: Basket API
version: 1.0.0
summary: |
  Internal HTTP and gRPC service for managing customer-scoped shopping baskets,
  Catalog price enrichment, and post-checkout cleanup.
readsFrom:
  - id: basket-database
    version: 1.0.0
writesTo:
  - id: basket-database
    version: 1.0.0
entities:
  - id: basket
    version: 1.0.0
  - id: basket-item
    version: 1.0.0
owners:
  - commerce-fulfillment-team
badges:
  - content: Internal
    backgroundColor: gray
    textColor: gray
  - content: HTTP + gRPC
    backgroundColor: teal
    textColor: teal
diagrams:
  - id: checkout-interaction
    version: 1.0.0
receives:
  - id: CreateBasket
    version: 1.0.0
    group: Basket Commands
  - id: UpdateBasket
    version: 1.0.0
    group: Basket Commands
  - id: DeleteBasket
    version: 1.0.0
    group: Basket Commands
  - id: GetBasket
    version: 1.0.0
    group: Basket Queries
  - id: GetBasketGrpc
    version: 1.0.0
    group: Basket Queries
  - id: PlaceOrderCommand
    version: 1.0.0
    from:
      - id: bookworm.{env}.finance.place-order
        version: 1.0.0
sends:
  - id: GetBookGrpc
    version: 1.0.0
    group: Catalog Queries
  - id: GetBooksGrpc
    version: 1.0.0
    group: Catalog Queries
  - id: BasketDeletedCompleteIntegrationEvent
    version: 1.0.0
    group: Basket Cleanup Outcomes
    to:
      - id: bookworm.{env}.basket.delete-complete
  - id: BasketDeletedFailedIntegrationEvent
    version: 1.0.0
    group: Basket Cleanup Outcomes
    to:
      - id: bookworm.{env}.basket.delete-failed
styles:
  icon: /icons/languages/dotnet.svg
specifications:
  - type: openapi
    path: openapi-v1.yml
    name: OpenAPI V1
  - type: asyncapi
    path: asyncapi-v1.yml
    name: AsyncAPI V1
repository:
  language: C#
  url: "https://github.com/foxminchan/BookWorm"
---

## Service Responsibility & Boundary

Basket API owns transient, customer-scoped shopping [[entity|basket]] and [[entity|basket-item]] state within the [[domain|shopping]] domain. It exposes authenticated HTTP endpoints for the storefront, serves internal gRPC basket snapshots to [[service|order-api]] during checkout, enriches basket reads with live titles and prices from [[service|catalog-api]] over gRPC, and performs asynchronous post-checkout cleanup with [[service|order-orchestration]] over Kafka.

## Service Profile

| Property                                  | Value                                                                                                                                                   |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Bounded Context / Domain**              | [[domain\|shopping]]                                                                                                                                    |
| **Owner Team**                            | [[team\|commerce-fulfillment-team]]                                                                                                                     |
| **Runtime Style**                         | REST API, gRPC Server/Client, and Async Kafka Consumer/Producer                                                                                         |
| **Public / Gateway Exposure**             | Yes via API Gateway (HTTP) and Internal Only (gRPC)                                                                                                     |
| **Authentication & Authorization Policy** | Microsoft Entra ID JWT via [[system\|identity-provider]]; `customer` role with basket read/write scopes; basket owner derived strictly from token       |
| **Owned Data Store(s)**                   | [[container\|basket-database]] (Redis key-value store, no SQL database)                                                                                 |
| **Key Resilience / Idempotency Pattern**  | 24-hour message-ID idempotency guard, per-user rate limiting, and dead-letter routing on [[channel\|bookworm.&#123;env&#125;.basket.dead-letter-queue]] |

## Contracts & Data Ownership

Basket API stores only customer ID, book IDs, and positive quantities in [[container|basket-database]]. Basket updates replace the entire item collection rather than merging partial changes, and basket records are never used to reconstruct accepted orders.

:::note
On read, Basket API batches distinct book IDs into a single gRPC lookup against [[service|catalog-api]] to attach current titles, regular prices, and sale prices. If Catalog returns no match for a book ID, the item remains in the response without inventing metadata.
:::

:::warning
Both Basket API and [[service|notification-api]] consume [[command|PlaceOrderCommand]] on the same Kafka topic. When [[service|order-orchestration]] retries on timeout, both consumers receive the retry.
:::

<MessageTable format="all" limit={15} showChannels={true} />

## Architecture Visualizations & Specifications

### Basket API Context

<MermaidFileLoader file="mermaids/BasketAPI-diagram-1.mmd" />

### Service Interactions

<NodeGraph />

### Owned Entities

<EntityMap />

## Attached Resources & Related Docs

- [[doc|platform/006-api-and-contracts]] — Consolidated HTTP, gRPC, and Kafka contract reference.
- [[container|basket-database]] — Redis key structure and durability characteristics.
- [[diagram|checkout-interaction]] — Interaction between Shopping, Ordering, and Finance.
- [[doc|domains/bookworm/subdomains/shopping/engineering/basket-api-contracts]] — Basket API contracts and boundaries.
- [[doc|domains/bookworm/subdomains/shopping/guides/checkout-lifecycle]] — Pre-order to checkout handoff guide.


 ## Raw Schema:openapi-v1.yml

openapi: 3.2.0
info:
  title: Basket Service API
  description: "Manages the lifecycle of customer shopping baskets, including adding and removing items, calculating totals, and handling checkout processes"
  contact:
    name: BookWorm Engineering
    url: https://github.com/foxminchan
    email: engineering@bookworm.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
  version: "1.0"
  summary: A service responsible for managing customer shopping baskets
paths:
  /api/v1/baskets:
    put:
      tags:
        - Basket
      summary: Update Basket
      description: Update a basket by its unique identifier
      operationId: UpdateBasketEndpoint
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/UpdateBasketCommand"
        required: true
      responses:
        "204":
          description: No Content
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
    get:
      tags:
        - Basket
      summary: Get Basket
      description: Get a basket by user
      operationId: GetBasketEndpoint
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CustomerBasketDto"
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
    delete:
      tags:
        - Basket
      summary: Delete Basket
      description: Delete a basket by its unique identifier
      operationId: DeleteBasketEndpoint
      responses:
        "204":
          description: No Content
        "404":
          description: Not Found
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetails"
    post:
      tags:
        - Basket
      summary: Create Basket
      description: Create a new basket for a user
      operationId: CreateBasketEndpoint
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateBasketCommand"
        required: true
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CustomerId"
        "400":
          description: Bad Request
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/HttpValidationProblemDetails"
components:
  schemas:
    BasketItemDto:
      required:
        - id
        - quantity
      type: object
      properties:
        id:
          type:
            - "null"
            - string
        quantity:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
        name:
          type:
            - "null"
            - string
        price:
          pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"
          type:
            - number
            - string
          format: double
          default: 0
        priceSale:
          pattern: "^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$"
          type:
            - "null"
            - number
            - string
          format: double
    BasketItemRequest:
      required:
        - id
        - quantity
      type: object
      properties:
        id:
          type: string
        quantity:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - integer
            - string
          format: int32
    CreateBasketCommand:
      required:
        - items
      type: object
      properties:
        items:
          type: array
          items:
            $ref: "#/components/schemas/BasketItemRequest"
    CustomerBasketDto:
      required:
        - id
        - items
      type: object
      properties:
        id:
          oneOf:
            - type: "null"
            - $ref: "#/components/schemas/CustomerId"
        items:
          type: array
          items:
            $ref: "#/components/schemas/BasketItemDto"
    CustomerId:
      type:
        - "null"
        - string
      items:
        type: string
    HttpValidationProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
        errors:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
    ProblemDetails:
      type: object
      properties:
        type:
          type:
            - "null"
            - string
        title:
          type:
            - "null"
            - string
        status:
          pattern: "^-?(?:0|[1-9]\\d*)$"
          type:
            - "null"
            - integer
            - string
          format: int32
        detail:
          type:
            - "null"
            - string
        instance:
          type:
            - "null"
            - string
    UpdateBasketCommand:
      required:
        - items
      type: object
      properties:
        items:
          type: array
          items:
            $ref: "#/components/schemas/BasketItemRequest"
tags:
  - name: Basket


 ## Raw Schema:asyncapi-v1.yml

asyncapi: 3.1.0
info:
  title: Basket API integration events
  version: 1.0.0
  description: |
    AsyncAPI contract for the Basket service's checkout cleanup events.
    Basket publishes a success or failure outcome after attempting to delete
    the submitted basket.
defaultContentType: application/cloudevents+json
channels:
  basketDeleteComplete:
    address: bookworm.{env}.basket.delete-complete
    description: Basket publishes this event when checkout cleanup deletes the basket successfully.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      basketDeleteComplete:
        $ref: "#/components/messages/BasketDeletedCompleteIntegrationEvent"
  basketDeleteFailed:
    address: bookworm.{env}.basket.delete-failed
    description: Basket publishes this event when checkout cleanup cannot delete the basket.
    parameters:
      env:
        $ref: "#/components/parameters/env"
    messages:
      basketDeleteFailed:
        $ref: "#/components/messages/BasketDeletedFailedIntegrationEvent"
operations:
  sendBasketDeleteComplete:
    action: send
    channel:
      $ref: "#/channels/basketDeleteComplete"
    summary: Publish successful basket deletion
    messages:
      - $ref: "#/channels/basketDeleteComplete/messages/basketDeleteComplete"
  sendBasketDeleteFailed:
    action: send
    channel:
      $ref: "#/channels/basketDeleteFailed"
    summary: Publish failed basket deletion
    messages:
      - $ref: "#/channels/basketDeleteFailed/messages/basketDeleteFailed"
components:
  parameters:
    env:
      description: BookWorm deployment environment.
      enum:
        - development
        - staging
        - production
      default: development
  messages:
    BasketDeletedCompleteIntegrationEvent:
      name: BasketDeletedCompleteIntegrationEvent
      title: Basket deletion completed
      summary: The submitted basket was deleted successfully after checkout.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/BasketDeletedCompletePayload"
    BasketDeletedFailedIntegrationEvent:
      name: BasketDeletedFailedIntegrationEvent
      title: Basket deletion failed
      summary: The submitted basket could not be deleted after checkout.
      contentType: application/json
      payload:
        $ref: "#/components/schemas/BasketDeletedFailedPayload"
  schemas:
    BasketDeletedCompletePayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - orderId
        - basketId
        - totalMoney
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier assigned by the integration-event building block.
        creationDate:
          type: string
          format: date-time
          description: UTC timestamp when the integration event was created.
        orderId:
          type: string
          format: uuid
          description: Identifier of the order whose submitted basket was deleted.
        basketId:
          type: string
          format: uuid
          description: Identifier of the basket deleted during checkout cleanup.
        totalMoney:
          type: number
          format: double
          description: Total purchase amount associated with the order.
    BasketDeletedFailedPayload:
      type: object
      additionalProperties: false
      required:
        - id
        - creationDate
        - orderId
        - basketId
        - totalMoney
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier assigned by the integration-event building block.
        creationDate:
          type: string
          format: date-time
          description: UTC timestamp when the integration event was created.
        orderId:
          type: string
          format: uuid
          description: Identifier of the order whose submitted basket could not be deleted.
        basketId:
          type: string
          format: uuid
          description: Identifier of the basket that could not be deleted.
        email:
          type:
            - string
            - "null"
          format: email
          description: Customer email used by downstream recovery or notification workflows.
        totalMoney:
          type: number
          format: double
          description: Total purchase amount associated with the order.
