Skip to main content

Overview

The Cart API provides endpoints for managing user shopping carts, including adding/removing items, viewing cart contents, and converting carts to orders during checkout. Base URL: /api/carrito Source: CarritoController.java

Authentication

All cart endpoints require user authentication. Each user has their own persistent cart identified by usuarioId.

Endpoints

Get User Cart

GET /api/carrito/{usuarioId}
Retrieve the user’s shopping cart. If the cart doesn’t exist, it will be automatically created. Authentication: Required
usuarioId
long
required
User ID
Response: 200 OK
id
long
Cart ID
usuario
object
User object with id, nombre, email
items
array
Array of cart item objects
total
double
Cart total (sum of all item subtotals)
Example Request:
cURL
curl -X GET http://localhost:8080/api/carrito/5 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
Example Response:
{
  "id": 12,
  "usuario": {
    "id": 5,
    "nombre": "Juan",
    "email": "juan.perez@example.com"
  },
  "items": [
    {
      "id": 45,
      "producto": {
        "id": 1,
        "nombre": "Laptop Dell XPS 15",
        "precio": 1299.99,
        "imagenes": [...]
      },
      "cantidad": 2,
      "subtotal": 2599.98
    }
  ],
  "total": 2599.98
}

Add Product to Cart

POST /api/carrito/{usuarioId}/agregar?productoId={productId}&cantidad={quantity}
Add a product to the user’s cart. If the product already exists in the cart, the quantity is incremented. Authentication: Required
usuarioId
long
required
User ID
productoId
long
required
Product ID to add
cantidad
integer
required
Quantity to add
Response: 200 OK - Updated cart object Example Request:
cURL
curl -X POST "http://localhost:8080/api/carrito/5/agregar?productoId=1&cantidad=2" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
If the product is already in the cart, the new quantity is added to the existing quantity. For example, if the cart has 2 units and you add 3 more, the total becomes 5 units.

Remove Product from Cart

DELETE /api/carrito/{usuarioId}/eliminar/{productoId}
Remove a specific product from the cart. Authentication: Required
usuarioId
long
required
User ID
productoId
long
required
Product ID to remove
Response: 200 OK - Updated cart object (without the removed item) Example Request:
cURL
curl -X DELETE http://localhost:8080/api/carrito/5/eliminar/1 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Clear Cart

DELETE /api/carrito/{usuarioId}/limpiar
Remove all items from the cart. Authentication: Required
usuarioId
long
required
User ID
Response: 200 OK - Empty response Example Request:
cURL
curl -X DELETE http://localhost:8080/api/carrito/5/limpiar \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Checkout (Convert Cart to Order)

POST /api/carrito/{usuarioId}/checkout
Convert the user’s cart into an order. This is the core checkout operation. Authentication: Required
usuarioId
long
required
User ID
Response: 200 OK - Created order object (see Orders API for structure) What Happens During Checkout:
1

Stock Validation

The system validates that sufficient stock exists for each product in the cart.
2

Order Creation

A new order is created with state PENDIENTE, containing all cart items.
3

Stock Deduction

Product stock quantities are automatically deducted.
4

Cart Cleared

The cart is emptied after successful order creation.
5

Email Notification

Order confirmation email is sent to the user.
Example Request:
cURL
curl -X POST http://localhost:8080/api/carrito/5/checkout \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
Success Response (200 OK):
{
  "id": 42,
  "usuario": {...},
  "total": 2599.98,
  "estado": "PENDIENTE",
  "fechaPedido": "2024-01-15T14:30:00",
  "detalles": [...]
}
Error Response (400 Bad Request):
"Stock insuficiente para el producto: Laptop Dell XPS 15"
Checkout will fail with a 400 error if any product in the cart has insufficient stock. The entire transaction is rolled back - no partial orders are created.

Cart Workflow

1

Browse Products

User views products using the Products API.
2

Add to Cart

User adds desired products to their cart via POST /api/carrito/{userId}/agregar.
3

Review Cart

User views cart contents via GET /api/carrito/{userId} to see total and items.
4

Adjust Quantities

User can add more of the same product (increments quantity) or remove items entirely.
5

Checkout

User proceeds to checkout via POST /api/carrito/{userId}/checkout, which creates an order.
6

Order Placed

Cart is emptied, order is created with status PENDIENTE, and confirmation email is sent.

Integration Examples

Frontend: Add Product to Cart

JavaScript
async function addToCart(userId, productId, quantity, token) {
  const response = await fetch(
    `http://localhost:8080/api/carrito/${userId}/agregar?productoId=${productId}&cantidad=${quantity}`,
    {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );
  
  const cart = await response.json();
  console.log('Cart updated:', cart);
  return cart;
}

// Usage: Add 2 units of product #1 to user #5's cart
await addToCart(5, 1, 2, userToken);

Frontend: Display Cart Summary

JavaScript
async function displayCart(userId, token) {
  const response = await fetch(`http://localhost:8080/api/carrito/${userId}`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  const cart = await response.json();
  
  console.log(`Cart Total: $${cart.total}`);
  cart.items.forEach(item => {
    console.log(`- ${item.producto.nombre} x${item.cantidad} = $${item.subtotal}`);
  });
}

Frontend: Checkout Process

JavaScript
async function checkout(userId, token) {
  try {
    const response = await fetch(`http://localhost:8080/api/carrito/${userId}/checkout`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    
    if (response.ok) {
      const order = await response.json();
      console.log('Order placed successfully!', order.id);
      // Redirect to order confirmation page
      window.location.href = `/orders/${order.id}`;
    } else {
      const error = await response.text();
      console.error('Checkout failed:', error);
      alert(`Error: ${error}`);
    }
  } catch (error) {
    console.error('Checkout error:', error);
  }
}

Cart Data Model

The cart consists of a Carrito entity and multiple CarritoItem entities: Carrito:
{
  "id": 12,
  "usuario": { "id": 5, "nombre": "Juan" },
  "items": [...],
  "total": 2599.98
}
CarritoItem:
{
  "id": 45,
  "producto": {
    "id": 1,
    "nombre": "Laptop Dell XPS 15",
    "precio": 1299.99
  },
  "cantidad": 2,
  "subtotal": 2599.98
}

Error Handling

Status CodeScenarioSolution
400 Bad RequestInsufficient stock during checkoutReduce quantity or wait for restock
400 Bad RequestProduct not foundVerify product ID exists
401 UnauthorizedMissing/invalid tokenRe-authenticate user
403 ForbiddenAccessing another user’s cartEnsure userId matches authenticated user
404 Not FoundUser does not existVerify user ID

Best Practices

Display a warning to users if product stock is low before they attempt checkout. Check product stock via the Products API.
The cart is persistent and tied to the user account. Users can add items, log out, and return later to find their cart intact.
The cart total is calculated server-side to prevent price tampering. Never trust client-side calculations for payment amounts.
Use database transactions to ensure stock deduction is atomic. If two users checkout the last item simultaneously, one will fail gracefully.

Products API

Browse and search products to add to cart

Orders API

View orders created from cart checkout

Cart Feature Guide

Learn about cart functionality

Build docs developers (and LLMs) love