My App
Cart

Update Cart Quantity

Update the quantity of items in the shopping cart

Overview

Update the quantity of an existing cart item using increment, decrement, or set actions. This endpoint provides flexible quantity management with automatic stock validation.

Endpoint

PATCH /v1/cart/update

Authentication

Requires the x-api-key header for authentication.

Request

Headers

HeaderTypeRequiredDescription
x-api-keystringYesYour API authentication key

Request Body

FieldTypeRequiredDescription
cartItemIdstringYesThe ID of the cart item to update
actionstringYesAction to perform: increment, decrement, or set
quantitynumberYesQuantity value (minimum: 1)

Actions Explained

  • increment: Adds the specified quantity to the current amount
  • decrement: Subtracts the specified quantity from the current amount
  • set: Sets the quantity to the exact specified value

Example Requests

async function updateCartQuantity(cartItemId, action, quantity) {
  const response = await fetch('https://api.yourstore.com/v1/cart/update', {
    method: 'PATCH',
    headers: {
      'x-api-key': process.env.BACKEND_API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      cartItemId,
      action,
      quantity
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to update cart');
  }

  return response.json();
}

// Increment by 1
updateCartQuantity('cart_123', 'increment', 1);

// Decrement by 1
updateCartQuantity('cart_123', 'decrement', 1);

// Set to specific quantity
updateCartQuantity('cart_123', 'set', 5);
type CartAction = 'increment' | 'decrement' | 'set';

interface UpdateCartRequest {
  cartItemId: string;
  action: CartAction;
  quantity: number;
}

interface CartItem {
  id: string;
  productId: string;
  quantity: number;
  price: number;
}

async function updateCartQuantity(
  cartItemId: string,
  action: CartAction,
  quantity: number
): Promise<CartItem[]> {
  const response = await fetch('https://api.yourstore.com/v1/cart/update', {
    method: 'PATCH',
    headers: {
      'x-api-key': process.env.BACKEND_API_KEY!,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      cartItemId,
      action,
      quantity
    } as UpdateCartRequest)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to update cart');
  }

  return response.json();
}

Server Action Example (Next.js)

'use server';

import { cookieManager } from '@/lib/auth-tools';
import { revalidatePath } from 'next/cache';

export async function updateCartAction(cartItemId, action, quantity) {
  try {
    const headers = await cookieManager.buildApiHeaders();
    
    const response = await fetch('https://api.yourstore.com/v1/cart/update', {
      method: 'PATCH',
      headers,
      body: JSON.stringify({ cartItemId, action, quantity })
    });

    if (!response.ok) {
      const error = await response.json();
      return { 
        success: false, 
        message: error.message 
      };
    }

    await cookieManager.handleApiResponse(response);
    const cart = await response.json();
    
    revalidatePath('/cart');
    
    return { 
      success: true, 
      cart 
    };
  } catch (error) {
    return { 
      success: false, 
      message: 'Failed to update cart' 
    };
  }
}
'use server';

import { cookieManager } from '@/lib/auth-tools';
import { revalidatePath } from 'next/cache';

type CartAction = 'increment' | 'decrement' | 'set';

interface UpdateCartResult {
  success: boolean;
  cart?: any[];
  message?: string;
}

export async function updateCartAction(
  cartItemId: string,
  action: CartAction,
  quantity: number
): Promise<UpdateCartResult> {
  try {
    const headers = await cookieManager.buildApiHeaders();
    
    const response = await fetch('https://api.yourstore.com/v1/cart/update', {
      method: 'PATCH',
      headers,
      body: JSON.stringify({ cartItemId, action, quantity })
    });

    if (!response.ok) {
      const error = await response.json();
      return { 
        success: false, 
        message: error.message 
      };
    }

    await cookieManager.handleApiResponse(response);
    const cart = await response.json();
    
    revalidatePath('/cart');
    
    return { 
      success: true, 
      cart 
    };
  } catch (error) {
    return { 
      success: false, 
      message: 'Failed to update cart' 
    };
  }
}

Quantity Selector Component

'use client';

import { updateCartAction } from '@/actions/cart';
import { useState } from 'react';

export function QuantitySelector({ cartItem }) {
  const [loading, setLoading] = useState(false);
  const [quantity, setQuantity] = useState(cartItem.quantity);

  const handleIncrement = async () => {
    setLoading(true);
    const result = await updateCartAction(cartItem.id, 'increment', 1);
    if (result.success) {
      setQuantity(prev => prev + 1);
    }
    setLoading(false);
  };

  const handleDecrement = async () => {
    if (quantity <= 1) return;
    
    setLoading(true);
    const result = await updateCartAction(cartItem.id, 'decrement', 1);
    if (result.success) {
      setQuantity(prev => prev - 1);
    }
    setLoading(false);
  };

  return (
    <div className="flex items-center gap-2">
      <button 
        onClick={handleDecrement} 
        disabled={loading || quantity <= 1}
      >
        -
      </button>
      <span>{quantity}</span>
      <button 
        onClick={handleIncrement} 
        disabled={loading}
      >
        +
      </button>
    </div>
  );
}

Response

Success Response (200)

Returns the updated cart items array.

[
  {
    "id": "cart_123",
    "productId": "prod_456",
    "quantity": 3,
    "price": 29.99,
    "product": {
      "name": "Wireless Headphones",
      "image": "https://example.com/images/headphones.jpg"
    }
  }
]

Error Responses

Status CodeDescription
401Invalid or missing API key
404Cart item not found
422Invalid input data or insufficient stock
500Failed to update cart quantity

Important Notes

Stock Validation: The API validates product stock availability. If the requested quantity exceeds available stock, you'll receive a 422 error with details about the maximum available quantity.

Automatic Removal: If you decrement a quantity to 0, consider using the Delete Cart Item endpoint instead for better UX.

Action Examples

Increment Example

{
  "cartItemId": "cart_123",
  "action": "increment",
  "quantity": 1
}

If current quantity is 2, it becomes 3.

Decrement Example

{
  "cartItemId": "cart_123",
  "action": "decrement",
  "quantity": 1
}

If current quantity is 3, it becomes 2.

Set Example

{
  "cartItemId": "cart_123",
  "action": "set",
  "quantity": 5
}

Sets quantity to exactly 5, regardless of current value.