0

I'm learning Magento 2 API. I need to create a custom API to get cart items and its stocks. I can see there is an API available to get cart items in Magento by default which is the below

GET V1/carts/mine/items

But I need to create a custom API to get the cart items. I'm not able to get the reference document to create it. Can anyone please help me how can I create custom API to get cart items and stocks.

Thanks in advance.

1 Answer 1

1

Have you tried, like this ?

app/code/VendorName/ModuleName/Model/ManageCart.php

<?php
namespace VendorName\ModuleName\Model;

class ManageCart implements \VendorName\ModuleName\Api\ManageCartInterface
{ 
    public function getItems()
    {
        // you can also pass parameter
        // your code here
    }
}

app/code/VendorName/ModuleName/Api/ManageCartInterface.php

<?php
namespace VendorName\ModuleName\Api;

interface ManageCartInterface
{
    /**
     * 
     * @api
     * @param  int|string $value
     * @return bool
     */
    public function getItems();
}

app/code/VendorName/ModuleName/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="VendorName\ModuleName\Api\ManageCartInterface" type="VendorName\ModuleName\Model\ManageCart"/>
</config>

app/code/VendorName/ModuleName/etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/managecart/getitems" method="POST">
        <service class="VendorName\ModuleName\Api\ManageCartInterface" method="getItems"/>
        <resources>
            <resource ref="anonymous" />
        </resources>
    </route>
</routes>

Then you can use:

rest/V1/managecart/getitems

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.