Magento 2 API Get Customer Cart Data using customer ID

Magento 2 API Get Customer Cart Data using customer ID

July 2, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento 2 API Get Customer Cart Data using customer ID

Title: Retrieving Customer Cart Data via API in Magento 2

Introduction

As an e-commerce developer working on a Magento 2 project, you may find it necessary to fetch customer cart data using the customer ID for various purposes such as serving data to mobile apps or integrating with third-party systems. In this post, we’ll guide you through the process of creating a custom API endpoint to achieve this.

Understanding the Problem

The provided code attempts to load customer cart data using the quoteModel and customerId, but it fails due to improper object creation and method usage. Let’s break down the issues:

  1. The quoteFactory is not properly initialized.
  2. The $this->quoteModel->loadByCustomerId() method does not exist in Magento 2.
  3. There are no proper validation checks for the customer ID.

Approach to Solving the Issue

To retrieve customer cart data using the customer ID, we’ll follow these steps:

  1. Create a custom API controller that extends Magento\Framework\App\Action\Action.
  2. Fetch the customer ID from the request parameters.
  3. Load the customer object and validate its existence.
  4. Retrieve the customer’s active quote (cart) using the appropriate Magento 2 methods.

Implementing the Solution

Let’s create a new API controller called CustomerCartController:

namespace LaravelCompany\Magento2Api\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Checkout\Model\Session as CheckoutSession;

class CustomerCartController extends Action
{
    private $checkoutSession;

    public function __construct(Context $context, CheckoutSession $checkoutSession)
    {
        $this->checkoutSession = $checkoutSession;
        parent::__construct($context);
    }

    public function execute()
    {
        $customerId = (int) $this->getRequest()->getParam('customer_id');
        if (!$customerId) {
            return $this->jsonResponse(['error' => 'Customer ID is required'], ResultFactory::TYPE_JSON);
        }

        $customer = $this->_objectManager->create(\Magento\Customer\Model\Customer::class)->load($customerId);
        if (!$customer->getId()) {
            return $this->jsonResponse(['error' => 'Invalid customer ID'], ResultFactory::TYPE_JSON);
        }

        $quote = $this->_objectManager->create(\Magento\Quote\Model\Quote::class);
        $customerQuote = $this->_objectManager->create(\Magento\Checkout\Model\Session::class)->getQuote();
        if ($customerQuote && $customerQuote->getId() === $customerId) {
            return $this->jsonResponse(['items' => $customerQuote->getAllVisibleItems()], ResultFactory::TYPE_JSON);
        }

        return $this->jsonResponse(['error' => 'Cart not found for the given customer ID'], ResultFactory::TYPE_JSON);
    }

    private function jsonResponse($data, $resultType)
    {
        $result = $this->resultFactory->create($resultType);
        $result->setData($data);

        return $result;
    }
}

In this example, we use the CheckoutSession to retrieve the active customer quote. We first validate the existence of a customer and then check if the loaded quote matches the provided customer ID.

Security Considerations

For security reasons, it is recommended to implement proper authentication and authorization mechanisms before accessing sensitive data like customer cart information. In this example, we assume that you have already implemented token-based authentication in your API setup.

You can incorporate additional checks such as validating the token’s signature or retrieving the customer ID from a secure user session.

Conclusion

In this post, we addressed the challenge of retrieving a Magento 2 customer’s cart data using their ID via a custom API endpoint. We identified the issues with the provided code and demonstrated how to create an appropriate controller to handle this request.

By following our approach and implementing the CustomerCartController in your project, you can efficiently fetch customer cart data while ensuring proper validation and security measures are in place.

Remember that working with Magento 2’s object manager directly is not recommended for production code. In a real-world scenario, use dependency injection or service managers to create objects in a more maintainable and secure manner.

For further reference on Magento 2 API development best practices, you can explore our dedicated tutorials and guides at Laravel Company.

Magento 2 Checkout API Customers

Our network