I am creating a custom api endpoint to receive some data in json format. This is my module’s code
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/matrid-nextapi/orders" method="POST">
<service class="MatridNextApiApiOrdersManagementInterface" method="postOrders"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
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="MatridNextApiApiOrdersManagementInterface" type="MatridNextApiModelOrdersManagement"/>
</config>
Api/OrdersManagementInterface.php
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
namespace MatridNextApiApi;
interface OrdersManagementInterface
{
/**
*
* @param mixed $data
* @return mixed[]
*/
public function postOrders($data);
}
Model/OrdersManagement.php
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
namespace MatridNextApiModel;
class OrdersManagement implements MatridNextApiApiOrdersManagementInterface
{
/**
*
* @param mixed $data
* @return mixed[]
*/
public function postOrders($data)
{
$data = json_decode($data);
echo "<pre>"; print_r($data);
}
}
Now I have created a script on magento root and try to hit this api using curl. I am expecting to get the posted array as result but I am getting an error message as response.
This is my custom script to check that is placed on magento root.
**custom-script.php**
<?php
$data = array (
"Orders"=> [
"ID"=> 1000006636,
"Brand"=> "Brand",
]
);
$ch = curl_init("https://staging.nonnon.co.uk/index.php/rest/V1/matrid-nextapi/orders");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($data))));
$result = curl_exec($ch);
echo "<pre>";print_r($result);
?>
This script is giving me output as
{"message":""%fieldName" is required. Enter and try again.","parameters":{"fieldName":"data"}}
I need the $data array as the output. I am not sure what I have missed as this is my first time working with magento apis. Could someone guide me in the right direction.
I just need $data as the response and then I will manipulate it according to my requirements.