1

How do I get a specific product via Element API?

Here's what i have so far

'api/product' => function() {
    $productId = craft()->request->getRequiredQuery( 'productId' );

    return [
        'elementType' => Product::class,
        // This provides Element API the fully qualified Element namespace + class.
        'pretty'      => true,
        'criteria'    => [
            'relatedTo' => [ 'targetElement' => $categoryIds ],
        ],
        'transformer' => function( Product $product ) {
            return [
                'title' => $product->title,
                'url'   => $product->url
            ];
        }

    ];
}   
1

If you want to get a specific product and it's variants by the productId you could simply do:

'api/product/<productId>' => function( $productId ) {
    return [
        'elementType' => Product::class,
        'criteria'    => [
            'id' => $productId
        ],
        'pretty'      => true,
        'transformer' => function( Product $product ) {
            foreach ( $product->getVariants() as $variant ) {
                $variants = [
                    'title'         => $variant->title,
                    'description'   => $variant->description,
                    'productId'     => (int) $variant->productId,
                    'purchasableId' => (int) $variant->purchasableId,
                    'status'        => $variant->status,
                    'type'          => $product->type->name,
                    'url'           => $product->url,
                ];
            }

            return $variants;
        },
    ];
},

you are able to get the product then via yourshop.domain/product/1234

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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