Magento2 REST API – How to Construct a HTTP Post Request

apimagento2rest

I construct a REST api using POST as follow

etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/module-webapi/etc/webapi.xsd">
    <route url="/V1/BonusPoint/updateFreeBonusPoint" method="POST">
        <service class="Vendor\BonusPoint\Api\BonusPointInterface" method="updateFreeBonusPoint"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Vendor\BonusPoint\Api\BonusPointInterface.php

<?php

namespace Vendor\BonusPoint\Api;

interface BonusPointInterface {

    /**
     * Update free bonus point of a customer.
     *
     * @api
     * @param int $customerId Customer ID.
     * @param int $point Free bonus point balance.
     * @return boolean True if success. Otherwise, false.
     */
    public function updateFreeBonusPoint($customerId, $point);
}

Vendor\BonusPoint\Model\BonusPoint.php

<?php

namespace Vendor\BonusPoint\Model;

use Vendor\BonusPoint\Api\BonusPointInterface;

class BonusPoint implements BonusPointInterface {

    protected $_customerBonusPointFactory;

    public function __construct(\Vendor\BonusPoint\Model\CustomerBonusPointFactory $customerBonusPointFactory) {
        $this->_customerBonusPointFactory = $customerBonusPointFactory;
    }

    public function updateFreeBonusPoint($customerId, $point) {
        try {
            $customerBonusPoint = $this->_customerBonusPointFactory->create();
            $customerBonusPoint->load($customerId);
            $customerBonusPoint->setFreeBonusPoint($point);
            $customerBonusPoint->save();
            return true;
        } catch (Exception $ex) {
            return false;
        }
    }

}

When I run curl to test:

curl -X POST "http://local.magento/index.php/rest/V1/BonusPoint/updateFreeBonusPoint" \
     -d "customerId=1&point=123" \
     -H "Authorization: Bearer soqsupye97th0sd0le136u3l933vto1o" 

It returns:

{
    "message": "Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded",
    "trace": null
}

What is the problem?

Best Answer

Magento do not support urlencoded requests.

Please specify content type: Add -H "Content-type: application/json" to curl command and send body as {"customerId": 1, "point":1 23}