2

Is there an API endpoint to return all shipping methods and carrier codes used in the store?

1

AFAIK, currently (When answered this question), there is no built-in API. We should create the custom one:

The most important thing is the class Magento\Shipping\Model\Config\Source\Allmethods::toOptionArray() will help us to get all the shipping methods or active methods.

app/code/Vendor/Shipping/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/shipping/methods" method="GET">
        <service class="Vendor\Shipping\Api\ShippingMethodInterface" method="getShippingMethods"/>
        <resources>
            <resource ref="Magento_Sales::sales" />
        </resources>
    </route>
</routes>

app/code/Vendor/Shipping/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="Vendor\Shipping\Api\ShippingMethodInterface"
                type="Vendor\Shipping\Model\ShippingMethod"/>
</config>

app/code/Vendor/Shipping/Api/ShippingMethodInterface.php

<?php

namespace Vendor\Shipping\Api;

/**
 * Interface retrieving shipping methods
 *
 * @api
 */

interface ShippingMethodInterface
{
    /**
     * Get shipping methods
     *
     * @return array
     */
    public function getShippingMethods();
}

app/code/Vendor/Shipping/Model/ShippingMethod.php

<?php

namespace Vendor\Shipping\Model;

use Magento\Shipping\Model\Config\Source\Allmethods;
use Vendor\Shipping\Api\ShippingMethodInterface;

class ShippingMethod implements ShippingMethodInterface
{
    /**
     * @var Allmethods
     */
    protected $allMethods;

    /**
     * ShippingMethod constructor.
     *
     * @param Allmethods $allMethods
     */
    public function __construct(
        Allmethods $allMethods
    ) {
         $this->allMethods = $allMethods;
    }

    /**
     * Getting active shipping methods
     *
     * @return array
     */
    public function getShippingMethods()
    {
         return $this->allMethods->toOptionArray(true);
    }
}

Remember to create the module xml and registration file.

| improve this answer | |
  • can u provide github/code link that not working for me – matinict Aug 12 '18 at 10:33

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.