Cart Management
Short Description: The Cart Management API provides comprehensive shopping cart functionality for the NextGate e-commerce platform. It supports adding products to cart, updating quantities, removing items, and real-time price calculations, stock validation, and automatic cart management with user authentication.validation.
Hints:
- All cart operations require user authentication via Bearer token
Cart is automatically created for each user upon first interaction- Each user has one persistent cart that maintains state across sessions
- Real-time stock validation prevents overselling
SupportsAddingaddingan existingproductsproductwithupdates its quantityupdatesReal-time price calculations include discounts and promotionsCart items are linked to active products only(ACTIVE status)Automatic cart cleanup when products become unavailableOptimized for concurrent access and inventory managementCart items show shop information for multi-vendor marketplace supportStock availability is validated on every cart operationadditive)- Cart persistence survives user logout/login cycles
Endpoints
1. Initialize Cart
Purpose: Creates or ensures cart exists for the authenticated user
Endpoint: POST /api/v1/cart/initialize
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
Response JSON Sample:
{
"success": true,
"message": "Shopping cart initialized successfully",
"data": null
}
Business Logic:
Creates new cart if user doesn't have oneReturns success if cart already existsAutomatic cart creation on first use
Error Responses:
2. Add Product to Cart
Purpose: Adds a product to the user's cart or updates quantity if already exists
Endpoint: POST /api/v1/cart/add
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Bearer token for authentication |
| Content-Type | string | Yes | application/json |
Request JSON Sample:
{
"productId": "456e7890-e89b-12d3-a456-426614174001",
"quantity": 2
}
Request Body Parameters:
| Parameter | Type | Required | Description | Validation |
|---|---|---|---|---|
| productId | UUID | Yes | ID of the product to add | |
| quantity | integer | Yes | Quantity to add to cart | Min: |
Response JSON Sample (New Item):
{
"success": true,
"message": "Product added to cart successfully",
"data": null
}
Response JSON Sample (Updated Existing):
{
"success": true,
"message": "Product quantity updated in cart successfully",
"data": null
}
Business Logic:
- Creates cart automatically if one doesn't exist
- If product already in cart, adds to existing quantity
- Validates total quantity doesn't exceed available stock
- Only allows active products to be added
Real-time stock validation
Stock Validation:
Checks product current stock before addingFor existing items: validates (current cart quantity + new quantity) ≤ stockPrevents overselling with detailed error messages
Error Responses:
400 Bad Request: Invalid productId or quantity validation error401 Unauthorized: Authentication required404 Not Found: Product not found or not active422 Unprocessable Entity: Insufficient stock available
Error Examples:
{
"success": false,
"message": "Insufficient stock for 'iPhone 15 Pro'. Only 3 units available",
"data": null
}
{
"success": false,
"message": "Cannot add more items. Total quantity (8) would exceed available stock (5) for 'MacBook Pro'",
"data": null
}
3.2. Get Shopping Cart
Purpose: Retrieves the complete shopping cart with all items, pricing,items and calculationspricing
Endpoint: GET /api/v1/cart
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Bearer token for authentication |
Response JSON Sample:
{
"success": true,
"message": "Shopping cart retrieved successfully",
"data": {
"user": {
"userId": "111e2222-e89b-12d3-a456-426614174003",
"userName": "john.doe",
"name": "John Doe"
},
"cartSummary": {
"totalItems": 3,2,
"totalQuantity": 7,3,
"subtotal": 2497.2198.00,
"totalDiscount": 200.0.00,
"totalAmount": 2297.2198.00
},
"cartItems": [
{
"itemId": "cart001-e89b-12d3-a456-426614174004",
"productId": "456e7890-e89b-12d3-a456-426614174001",
"productName": "iPhone 15 Pro Max 512GB",
"productSlug": "iphone-15-pro-max-512gb",
"productImage": "https://example.com/images/iphone15-pro-max.jpg",
"productType": "PHYSICAL",
"unitPrice": 1199.00,
"discountAmount": 100.00,
"quantity": 2,
"itemSubtotal": 2398.00,
"itemDiscount": 200.00,
"totalPrice": 2198.2398.00,
"shop": {
"shopId": "123e4567-e89b-12d3-a456-426614174000",
"shopName": "TechStore Pro",
"shopSlug": "techstore-pro",
"logoUrl": "https://example.com/logos/techstore-pro.png"
},
"availability": {
"inStock": true,
"stockQuantity"availableQuantity": 2525,
"maxPerCustomer": 5
},
"addedAt": "2025-09-23T10:30:00Z"
},
{
"itemId": "cart002-e89b-12d3-a456-426614174005",
"productId": "567e8901-e89b-12d3-a456-426614174002",
"productName": "MacBook Air M3",
"productSlug": "macbook-air-m3",
"productImage": "https://example.com/images/macbook-air-m3.jpg",
"productType": "PHYSICAL",
"unitPrice": 999.00,
"discountAmount": 0.00,
"quantity": 1,
"itemSubtotal": 999.00,
"itemDiscount": 0.00,
"totalPrice": 999.00,
"shop": {
"shopId": "123e4567-e89b-12d3-a456-426614174000",
"shopName": "TechStore Pro",
"shopSlug": "techstore-pro",
"logoUrl": "https://example.com/logos/techstore-pro.png"
},
"availability": {
"inStock": true,
"stockQuantity"availableQuantity": 88,
"maxPerCustomer": null
},
"addedAt": "2025-09-23T11:15:00Z"
}
],
"updatedAt": "2025-09-23T14:20:00Z"
}
}
Response Structure:
User Summary
| Field | Description |
|---|---|
| userId | Unique identifier of the cart owner |
| userName | User's login username |
| name | User's full name (firstName + lastName) |
Cart Summary
| Field | Description |
|---|---|
| totalItems | Number of distinct products in cart |
| totalQuantity | Total quantity of all items combined |
| subtotal | Total price before discounts |
| totalDiscount | Total discount amount applied |
| totalAmount | Final amount after discounts |
Cart Item Details
| Field | Description |
|---|---|
| itemId | Unique identifier for the cart item |
| productId | Product identifier |
| productName | Current product name |
| productSlug | URL-friendly product identifier |
| productImage | Primary product image URL |
| productType | PHYSICAL or DIGITAL |
| unitPrice | Current product price per unit |
| quantity | Quantity of this product in cart |
| itemSubtotal | unitPrice × quantity |
| totalPrice | itemSubtotal |
| shop | Shop information (id, name, slug, logo) |
| availability | Real-time stock information |
| addedAt | When item was first added to cart |
Real-timeProduct
Calculations:
PricesreflectcurrentField Description inStock Whether the product pricingisDiscountscurrentlyappliedinautomaticallystockforsaleitemsavailableQuantity StockCurrent quantitiesavailableshowinventoryreal-timeavailabilityCalculationsmaxPerCustomer updatedMaximum onquantityeachacartsingleretrievalcustomer can purchase (null if no limit)
Error Responses:
4.3. Update Cart Item Quantity
Purpose: Updates the quantity of a specific item in the cart
Endpoint: PUT /api/v1/cart/items/{itemId}
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Bearer token for authentication |
| Content-Type | string | Yes | application/json |
Path Parameters:
| Parameter | Type | Required | Description | |
|---|---|---|---|---|
| itemId | UUID | Yes | ID of the cart item to update |
Request JSON Sample:
{
"quantity": 3
}
Request Body Parameters:
| Parameter | Type | Required | Description | Validation |
|---|---|---|---|---|
| quantity | integer | Yes | New quantity for the cart item | Min: |
Response JSON Sample:
{
"success": true,
"message": "Product quantity updated successfully",
"data": null
}
Business Logic:
- Updates quantity to the exact specified value (not additive)
- Validates new quantity doesn't exceed current stock
- Only allows updating items in the authenticated user's own cart
items
Stock Validation:
Checks current product stock before updatingPrevents quantity exceeding available inventoryProvides detailed error message if stock insufficient
Error Responses:
400 Bad Request: Invalid quantity value401 Unauthorized: Authentication required404 Not Found: Cart item not found in user's cart422 Unprocessable Entity: Insufficient stock for requested quantity
Error Example:
{
"success": false,
"message": "Insufficient stock for 'iPhone 15 Pro'. Only 2 units available",
"data": null
}
5.4. Remove Cart Item
Purpose: Removes a specific item completely from the cart
Endpoint: DELETE /api/v1/cart/items/{itemId}
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Bearer token for authentication |
Path Parameters:
| Parameter | Type | Required | Description | |
|---|---|---|---|---|
| itemId | UUID | Yes | ID of the cart item to remove |
Response JSON Sample:
{
"success": true,
"message": "Product removed from cart successfully",
"data": null
}
Business Logic:
- Completely removes the cart item and all its quantity
- Only allows removing items from the authenticated user's own cart
items Cart item is permanently deleted from database
Error Responses:
6.5. Clear Shopping Cart
Purpose: Removes all items from the user's cart
Endpoint: DELETE /api/v1/cart/clear
Access Level: 🔒 Protected (Requires authentication)
Authentication: Bearer Token
Request Headers:
| Header | Type | Required | Description |
|---|---|---|---|
| Authorization | string | Yes | Bearer token for authentication |
Response JSON Sample:
{
"success": true,
"message": "Shopping cart cleared successfully",
"data": null
}
Business Logic:
- Removes all cart items for the authenticated user
- Cart entity remains but becomes empty
Cannot be undone - permanent deletion of all items
Use Cases:
User wants to start fresh with empty cartClear cart after successful order completionAdministrative cart cleanup
Error Responses:
Quick Reference Guide
Common HTTP Status Codes
200 OK: Successful GET/PUT/DELETE request201 Created: Successful POST request (cart initialization)400 Bad Request: Invalid request data or validation errors401 Unauthorized: Authentication required or invalid token404 Not Found: Cart item, product, or user not found422 Unprocessable Entity: Stock validation errors500 Internal Server Error: Server error during processing
Authentication Requirements
Bearer Token: IncludeAuthorization: Bearer your_tokenin headersAll endpoints require authentication- no public cart operationsUser-specific carts- each user has their own isolated cart
Data Format Standards
Dates: Use ISO 8601 format (2025-09-23T14:30:00Z)Prices: Decimal with 2 decimal places (999.00)UUIDs: Standard UUID format (123e4567-e89b-12d3-a456-426614174000)Quantities: Positive integers only (minimum 1)
Cart Business Rules
Stock Management
Real-time Validation: Stock checked on every cart operationPrevent Overselling: Cannot add more than available inventoryActive Products Only: Only products with ACTIVE status can be addedStock Updates: Cart shows current stock, not stock at time of adding
Quantity Management
Minimum Quantity: All quantities must be at least 1Additive Adding: Adding existing product increases quantityAbsolute Updates: Update operations set exact quantity (not additive)Stock Limits: Cannot exceed available inventory at any time
Cart Persistence
User-Specific: Each authenticated user has one persistent cartSession Independent: Cart survives logout/login cyclesAutomatic Creation: Cart created automatically on first interactionCleanup: No automatic expiration (persists indefinitely)
Price Calculation Logic
Item-Level Calculations
Item Subtotal = Unit Price × Quantity
Item Discount = Discount Amount × Quantity (if product on sale)
Item Total = Item Subtotal - Item Discount
Cart-Level Calculations
Total Items = Count of distinct products
Total Quantity = Sum of all item quantities
Subtotal = Sum of all item subtotals
Total Discount = Sum of all item discounts
Total Amount = Subtotal - Total Discount
Real-time Price Updates
Prices reflect current product pricing on each cart retrievalDiscounts applied automatically for products on saleNo price locking - prices may change between cart operations
Error Handling Patterns
Stock Validation Errors
{
"success": false,
"message": "Insufficient stock for '{productName}'. Only {available} units available"
}
Cart Item Not Found
{
"success": false,
"message": "Cart item not found"
}
Authentication Errors
{
"success": false,
"message": "User not authenticated"
}
Best Practices for Cart Management
For Frontend Applications
Check stock before adding- validate availability client-side when possibleHandle stock errors gracefully- show clear messages about availabilityRefresh cart regularly- prices and stock change in real-timeImplement quantity controls- prevent users from entering invalid quantitiesShow loading states- cart operations may take time due to validationCache cart data briefly- but refresh before checkoutHandle authentication errors- redirect to login when tokens expireDisplay shop information- help users understand multi-vendor itemsShow stock warnings- alert users about low stock itemsImplement optimistic updates- with fallback for failures
For Backend Integration
Always authenticate usersbefore cart operationsValidate stock in real-time- inventory changes frequentlyHandle concurrent access- multiple devices may access same cartLog cart operations- for debugging and analyticsMonitor stock levels- prevent overselling scenariosImplement rate limiting- prevent cart abuseClean up orphaned items- when products become inactiveValidate product availability- ensure products are still activeHandle shop changes- when products move between shopsImplement cart recovery- for interrupted operations
Common Use Cases
Add to Cart: POST /api/v1/cart/add with productId and quantityView Cart: GET /api/v1/cart for complete cart with calculationsUpdate Quantity: PUT /api/v1/cart/items/{itemId} with new quantityRemove Item: DELETE /api/v1/cart/items/{itemId}Clear Cart: DELETE /api/v1/cart/clear
Validation Summary
All endpoints require authenticationStock validation on add/update operationsOnly active products can be added to cartQuantities must be positive integers (minimum 1)Real-time price calculations on cart retrieval