Having issues looping through variants for Commerce 2 Products using Element API I'm currently able to return the first variant using the following:

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

return [
  'endpoints' =&gt; [
    'products.json' =&gt; function () {
      return [
        'elementType' =&gt; Product::class,
        'paginate' =&gt; false,
        'pretty' =&gt; true,
        'criteria' =&gt; [
          // 'id' =&gt; $productId,
        ],
        'transformer' =&gt; function (Product $product) {
          foreach ( $product-&gt;getVariants() as $variant ) {
            $variants = [
              'type'          =&gt; $product-&gt;type-&gt;name,
              'title'         =&gt; $variant-&gt;title,
              'sku'           =&gt; $variant-&gt;sku,
              'price'         =&gt; $variant-&gt;price,
              'stock'         =&gt; $variant-&gt;stock,
              'intro'         =&gt; $variant-&gt;intro,
              'purchasableId' =&gt; (int) $variant-&gt;purchasableId,
              'status'        =&gt; $variant-&gt;status,
              'url'           =&gt; $variant-&gt;url,
              // 'productPhoto'  =&gt; $variant-&gt;productPhoto
            ];
          }

          return $variants;
        }
      ];
    }
  ]
]
?&gt;


Which returns:

{
  data: [
    {
      type: "Shakes",
      title: "3 Month Supply",
      sku: "mvn-a03m",
      price: "100.0000",
      stock: "0",
      intro: "&lt;p&gt;This is another 3M variant&lt;/p&gt;",
      purchasableId: 37,
      status: "enabled",
      url: "https://testing.kamicrafted.com/shop/products/mavenshake?variant=37"
    }
  ]
}


The issue is that I currently have 3 variants set for this product yet the json response only shows the last variant within the set.

I'm completely stumped at this point and was hoping someone had a similar experience with a solution to this issue.
You are setting the whole $variants variable to last item in the array instead of creating the $variants array variable and pushing items into it. Should be this:

'transformer' =&gt; function (Product $product) {
          $variants = [];

          foreach ( $product-&gt;getVariants() as $variant ) {
            $variants[] = [
              'type'          =&gt; $product-&gt;type-&gt;name,
              'title'         =&gt; $variant-&gt;title,
              'sku'           =&gt; $variant-&gt;sku,
              'price'         =&gt; $variant-&gt;price,
              'stock'         =&gt; $variant-&gt;stock,
              'intro'         =&gt; $variant-&gt;intro,
              'purchasableId' =&gt; (int) $variant-&gt;purchasableId,
              'status'        =&gt; $variant-&gt;status,
              'url'           =&gt; $variant-&gt;url,
              // 'productPhoto'  =&gt; $variant-&gt;productPhoto
            ];
          }

          return $variants;
        }