2

I am trying to get Products using the Element API plugin. I set the 'elementType' to Commerce_Products, CommerceProducts, etc.., but the endpoint keeps returning:

Endpoint has an invalid elementType

This is my endpoint:

use craft\commerce\elements\Product as ProductsModel;

return [
    'endpoints' => [
        'api/search' => [
            'elementType' => 'ProductsModel',
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => (Craft::$app->request->getParam('keyName')) ? 'title:'.'*'.Craft::$app->request->getParam('keyName').'*' : ''
            ],
            'transformer' => function(ProductsModel $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ],
    ]
];

How do I fix it?

1
  • How can i return image url for product?
    – user11651
    Commented Mar 12, 2021 at 6:40

1 Answer 1

3

You're so close! Just one change (see the elementType key, and the added comment)…

use craft\commerce\elements\Product;

return [
    'endpoints' => [
        'api/search' => [
            'elementType' => Product::class, // This provides Element API the fully qualified Element namespace + class.
            'paginate' => false,
            'pretty' => true,
            'criteria' => [
                'limit' => 15,
                'search' => (Craft::$app->request->getParam('keyName')) ? 'title:'.'*'.Craft::$app->request->getParam('keyName').'*' : ''
            ],
            'transformer' => function(Product $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url
                ];
            },
        ],
    ]
]

Note: I'd recommend leaving the use statement as just Product, as I've done above. What you're importing is a class that inherits from the Craft Element class… “Model” has some other specific connotations in Craft + Yii, and even though at a lower level, Elements are still models, I think it's a good idea to leave them named as-is… after all, this is the Element API! 😉

1
  • 1
    For those curious folks out there, this is effectively no different than providing a string 'craft\commerce\elements\Product', but Craft 3 seems to express a pretty strong preference for the ::class constant, instead. Commented Dec 10, 2018 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.