Exposing current Commerce2 Cart via the Element API I want to be able to retrieve the current users Cart via a JSON API endpoint, so I can loop through the products in the cart in JS on the front end. 

I've got the Element API plugin installed, but I am not understanding how to grab the current cart from inside the endpoint via PHP. Any help much appreciated.

&lt;?php
use craft\helpers\UrlHelper;
use craft\commerce\elements\Product;
use craft\commerce\elements\Order;

function requireLogin() {
    $currentUser = Craft::$app-&gt;user-&gt;getIdentity();

    if(!$currentUser) {
        throw new \yii\web\ForbiddenHttpException("You are not logged in");
    }
}

function requireCart() {
    // TWIG would be: {% set cart = craft.commerce.getCarts().getCart() %}
    $currentCart = Craft::WHAT?;
    $cartId      = $currentCart-&gt;id;

    if(!$currentCart) {
        throw new \yii\web\ForbiddenHttpException("You don't have a cart yet");
    }
}

return [
    'endpoints' =&gt; [
        'cart.json' =&gt; function() {
            requireLogin();
            requireCart();

            \Craft::$app-&gt;response-&gt;headers-&gt;set('Access-Control-Allow-Origin', '*');

            return [
                'elementType' =&gt; Order::class,
                'criteria'    =&gt; ['id' =&gt; $cartId],
                'transformer' =&gt; function(Order $order) {
                    $items = [];

                    foreach($order-&gt;lineItems as $lineItem) {
                        $items[] = [array(
                            'itemTitle' =&gt; $lineItem-&gt;title
                        )];
                    }

                    return [
                        'items' =&gt; $items
                    ];
                }
            ];
        }
    ]
]
?&gt;
The cart is not baked into \Craft, but craft\commerce\Plugin.

Try the following:

$cart = craft\commerce\Plugin::getInstance()-&gt;getCarts()-&gt;getCart();


Uses the following function:

/**
 * Get the current cart for this session.
 *
 * @param bool $forceSave Force the cart to save when requesting it.
 * @return Order
 * @throws Exception
 * @throws \Throwable
 * @throws \craft\errors\ElementNotFoundException
 */
public function getCart($forceSave = false): Order